Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-model not working inside ng-include

I am a beginner in angularjs and currently I am facing an issue with ng-include.

I have a test app using partials. Here is my code.

<html ng-app ="TextboxExample">
    <head>
        <title>Settings</title>
        <script src="angular.js"></script>
  </head>

    <body ng-controller="ExampleController">
        <div ng-include src = "'view.html'"></div>
        <script>
          angular.module('TextboxExample', [])
            .controller('ExampleController', ['$scope', function($scope) {
              $scope.textboxVal = 'fddfd';

              $scope.ReadGeneralSettings = function() {
                alert($scope.textboxVal);
              }
              $scope.ResetGeneralSettings = function() {

                $scope.textboxVal = 'fddfd';
              }

            }]);
        </script>
        <button class="pull-right" ng-click = "ReadGeneralSettings()">Read</button>
        <button class="pull-right" ng-click = "ResetGeneralSettings()">Cancel</button>



    </body>
</html>

The partial code view.html is

<input type="text" ng-model="textboxVal">

For some reason, textboxVal set to ng-model doesn't get updated when I enter the value in the text box. But this works fine if I don't use ng-include and directly add the content of view.html into the main html file. Please help.

Thanks Sunil

like image 378
S_R Avatar asked Sep 25 '15 05:09

S_R


2 Answers

Use $parent to access the scope of the controller

Demo

<input type="text" ng-model="$parent.textboxVal">
like image 101
Shamal Perera Avatar answered Nov 19 '22 09:11

Shamal Perera


The problem is that ngInclude creates new scope, so the model you define inside partial template with ngModel works with local scope value, and outer ExampleController can't see it.

The simple solution is to use prototypical chain of scope objects, then inner scope will inherit and use model value from the outer scope:

<body ng-controller="ExampleController">
    <div ng-include src = "'view.html'"></div>
    <script>
      angular.module('TextboxExample', [])
        .controller('ExampleController', ['$scope', function($scope) {
          $scope.model.textboxVal = 'fddfd';

          $scope.ReadGeneralSettings = function() {
            alert($scope.model.textboxVal);
          }
          $scope.ResetGeneralSettings = function() {
            $scope.model.textboxVal = 'fddfd';
          }

        }]);
    </script>
    <button class="pull-right" ng-click = "ReadGeneralSettings()">Read</button>
    <button class="pull-right" ng-click = "ResetGeneralSettings()">Cancel</button>

</body>

and then use it in partial as

<input type="text" ng-model="model.textboxVal">
like image 4
dfsq Avatar answered Nov 19 '22 09:11

dfsq