1

I am new to Angular JS, and I am learning it through the tutorials,

my question is why my model is not updating the view?

Following is the code.

<!DOCTYPE html>

<div ng-controller="MyContr">
    {{xxx}}
</div>


<input type="text"  ng-model="xxx" ng-controller="MyContr" />
    <script>
    var app = angular
              .module("MyApp", [])
              .controller("MyContr", function ($scope) {
                  var xxx="Alexander"
                  $scope.xxx = xxx;
                 });
</script>

AT82
  • 71,416
  • 24
  • 140
  • 167
Alexander Zaldostanov
  • 2,907
  • 4
  • 30
  • 39

1 Answers1

1

According to the code shown on the question, It seems that your are calling MyContr twice,

one here:

<div ng-controller="MyContr">
    {{xxx}} <!-- xxx (instance 1) -->
</div>

and another here:

<!-- xxx (instance 2) --> 
<input type="text"  ng-model="xxx" ng-controller="MyContr" />

... so two (different) instances of the same controller are being created. This way each instance have two different xxx var, each one has its own xxx variable on its scope.

Solution

Option 1 - You can share the data between instances (see Share data between AngularJS controllers and AngularJS: How can I pass variables between controllers?)

Option 2 - Enclose both html elements inside the same instance of the MyContr like this:

<span ng-controller="MyContr">
    <div>
        {{xxx}}
    </div>
    <input type="text"  ng-model="xxx" />
</span>
Community
  • 1
  • 1
lealceldeiro
  • 14,342
  • 6
  • 49
  • 80
  • Thanks so much for this solution. I've been working on a similar problem on and off for weeks. In my case, I didn't have multiple ng-controller tags, but had one in first div and other divs didn't recognize it. Enclosed all divs in a parent div and moved ng tags there, and it worked. – RMittelman Jun 30 '17 at 20:27