2015-10-12 65 views
0

我有一個指令,從工廠獲取其數據。它在第一次加載時工作正常。但稍後,當工廠數據發生變化時,指令不會對這些更改做出反應。我該如何解決它?角度:更新指令時,注入工廠更改數據

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

回答

1

嘗試使用

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

$ watchCollection 「淺手錶的對象和火災的屬性每當任何屬性改變」 AngularJs Docs

我建立一個小應用程序複製你的問題。這裏是Demo

+0

空操作(它並不能幫助 –

+0

你可以把你的代碼上plunker –

+0

的http:// codepen。 io/anon/pen/xwLLxM?editors = 101 –

0
setTimeout(function(){ 
    $scope.$apply() 
},0); 

把這個數據更新用後,該VL更新UI 可能工作