2014-11-06 63 views
1

我在我的應用程序中有一個控制器,它在$ http調用後分配一個值。AngularJS隔離範圍在控制器分配新值後沒有更新

我希望我的指令反映該值的變化,但$ watch沒有看到變化。我在隔離範圍上使用雙向綁定來嘗試查看該值的更改。

因此,對於控制器我有

angular.module('myApp', []) 
    .controller('myCtrl', ['$scope', '$http', function ($scope, $http) { 

    console.log('first point'); 

    $http.get('some/URL').success(function(data) { 
     $scope.response = data; 
     $scope.chartValues = $scope.response.data; 
     console.log('chartValues assigned'); 
    }); 
    console.log('second point'); 
}]); 

現在,在我的指導我有

angular.module('myDirectives, []) 
    .directive('myChart', [function() { 
    return { 
     template: '<h3>hello</h3>', 
     restrict: 'EA', 
     scope: { data: '=chartData' }, 
     link: function (scope, element, attrs) { 

      scope.$watch('scope.data', function (newVals) { 
      console.log('data was changed!'); 
      console.log(newVals); 
      }, true); 
    } 
} 

的部分包括:

<my-chart chart-data="chartValues"></my-chart> 

控制檯將日誌:

first point 
second point 
data was changed! 
undefined 
chartValues assigned 

它只是停在那裏。看起來好像範圍$ watch一直注意到chartValues被更新,即使我已經告訴隔離範圍中的'data'與parent範圍中的chartValues同步。的

scope.$watch('scope.data', function (newVals) { 

回答

1

1

使用

scope.$watch('data', function (newVals) { 

,而不是你的問題似乎是'data'您應該使用'scope.data'

所以它會看起來像scope.$watch('scope.data', function (newVals)