PeteGO PeteGO - 2 months ago 6
AngularJS Question

Angular - changes to directive controller's scope aren't reflected in view

Changes to my scope variable

foo
are getting updated in the html. When that value is change inside the scope of a directive's controller, it isn't updating in the html.

What do I need to do to make it update?

I have a simple example:


app.js


var app = angular.module('app', []);

app.controller('ctrl', function($scope) {
$scope.foo = 99;

$scope.changeValue = function() {
$scope.foo = $scope.foo + 1;
}
});

app.directive('d1', function(){
return {
restrict: 'E',
scope: {
theFoo: '='
},
templateUrl: 'd1.html',
controller: 'd1Ctrl',
}
});

app.controller('d1Ctrl', function($scope) {
$scope.test = $scope.theFoo;
});



d1.html


<div>
<p>The value of foo is '{{theFoo}}'.</p>
<p>The value of test is '{{test}}'.</p>
</div>



inside index.html


<d1 the-foo='foo'>
</d1>

<button ng-click='changeValue()'>change value</button>


So in summary,
{{theFoo}}
is updating, but
{{test}}
isn't. Why?

Answer

The reason is that $scope.foo value is a primitive.

In the directive controller you only assign $scope.test once when controller initializes. Primitives have no inheritance the way objects do so there is nothing that would change $scope.test after that initial assignment

If you used an object instead to pass in ... inheritance would be in effect and you would see changes...otherwise you would need to watch $scope.theFoo and do updates to $scope.test yourself