I have encountered problem with updating data in AngularJS directive.
The directive loads list of orders when initialized, and then watches the variable orderMade. If this variable is changed, it should reload the list of orders.
.directive('listRingorders', ['ringsService',function(ringsService){
return {
restrict: 'AE',
templateUrl : 'pages/list-ringorders.tpl.html',
scope : {
orderMade : '='
},
controllerAs : 'RingOrderListCtrl',
bindToController: true,
controller : function (){
// variables
var self = this;
// load data
ringsService.fetchRingOrders()
.then(function(data){
self.ringorders = data;
}, function(data){
alert("Error");
});
//log orders
this.test = function(){
console.log(self.ringorders);
}
},
link: function (scope, element, attrs) {
scope.$parent.$watch(attrs.orderMade, function() {
ringsService.fetchRingOrders()
.then(function(data){
scope.ringorders = data;
}, function(data){
alert("Error");
});
});
}
}
}]);
And here is html template (simplyfied)
<div ng-repeat="ringOrder in RingOrderListCtrl.ringorders">
<h3>Order number: {{ringOrder.ID}}</h3>
</div>
I can correctly capture changing value orderMade and reload data, but when I update the scope.ringorders variable, the list does not update (HTML page shows the same data). Also when I log self.ringorders in controller's test() function, it contains old data.
My question is: how to update directive's scope data from link function?
UPDATE
I have figured out the solution - I was accessing the scope of controller function in directive instead of accesing teh scope of directive itself.
Here is correct template (just replace RingOrderListCtrl.ringorders with ringorders)
<div ng-repeat="ringOrder in ringorders">
<h3>Order number: {{ringOrder.ID}}</h3>
</div>
scope.$apply()in yourthenmethod after you added ringorders to scope?scope.$applycausesError: [$rootScope:inprog] $digest already in progressringServicemaybe that helps to see the issue?