【问题标题】:angular: update directive when injected factory change data角度:注入工厂更改数据时更新指令
【发布时间】:2015-10-12 12:33:24
【问题描述】:

我有一个从工厂获取数据的指令。第一次加载时,它工作正常。但后来,当工厂数据发生变化时,指令不会对此变化做出反应。我该如何解决?

appWD.directive('widgetName', ['WidgetData', function(WidgetData) {
    return {
        restrict: 'E',
        templateUrl: '_widget.html',
        link: function(scope, elem, attrs) {
            scope.data = WidgetData.GetWidgetData('widgetName');
            //both do not work
            //scope.$watch(scope.data);
            //scope.$watch(WidgetData.GetWidgetData('widgetName'));
        }
    };
}]);

GetWidgetData('widgetName') 返回对象。

codepen 示例:http://codepen.io/anon/pen/xwLLxM?editors=101

【问题讨论】:

    标签: angularjs angular-directive angularjs-factory


    【解决方案1】:

    尝试使用

    scope.$watchCollection(function(){return WidgetData.getWidgetData('widget');}, function() {
        alert('scope.$watchCollection');
     });
    

    $watchCollection“浅层监视对象的属性并在任何属性更改时触发”AngularJs Docs

    我创建了一个小应用程序来复制您的问题。这是Demo

    【讨论】:

    【解决方案2】:
    setTimeout(function(){
        $scope.$apply()
    },0);
    

    把这个放在数据更新之后,这个 vl 更新 UI 可以工作

    【讨论】:

      猜你喜欢
      • 2014-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-24
      • 1970-01-01
      • 1970-01-01
      • 2015-12-14
      • 2016-07-06
      相关资源
      最近更新 更多