javascript - Controller 分配新值后AngularJS隔离范围不更新

标签 javascript angularjs

我的应用程序中有一个 Controller ,它在 $http 调用后分配一个值。

我希望我的指令反射(reflect)该值的变化,但是 $watch 没有看到变化。我在隔离范围上使用双向绑定(bind)来尝试查看该值的变化。

所以对于 Controller 我有

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

它就停在那里。似乎 scope.$watch 没有注意到 chartValues 已更新,即使我已经告诉隔离范围中的“数据”与父范围中的 chartValues 同步。

最佳答案

您的问题似乎是 'data'您应该使用 'scope.data' .

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

关于javascript - Controller 分配新值后AngularJS隔离范围不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26780934/

相关文章:

javascript - 在 page.evaluate 中等待 page.waitFor ?

javascript - 在javascript中异步函数之后运行函数

angularjs - 使用 angularjs 编写自定义 "editable"指令

json - Angular gzip json 文件自动 : Refused to set unsafe header "Accept-Encoding"

javascript - Ng-options 选择值作为 int 而不是字符串

javascript - 如何从html ng-click调用链接功能方法?

javascript - jQuery parent 选择器 - 遍历

javascript - 允许 infinitescroll.js 运行 X 次,然后加载更多帖子

javascript - 短作用域命名空间数组是什么意思?

angularjs - Bootstrap 3 Angular 模式弹出窗口不处理移动设备上的触摸事件