PeteGO PeteGO - 10 months ago 38
AngularJS Question

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

Changes to my scope variable

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:


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

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

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

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

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


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

inside index.html

<d1 the-foo='foo'>

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

So in summary,
is updating, but
isn't. Why?

Answer Source

The reason is that $ 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