In my directive, I have a controller variable, page which gets incremented when you press the button in the directive. However, the next line, scope.alertPage()
which calls the controller function does not reflect this change. Notice, when you click the button page is still alerted as 1!
I know I can fix this by adding $scope.$apply in the controller but then I get the error that says a digest is already taking place.
Plunker
app = angular.module('app', []);
app.controller('myCtrl', function($scope) {
$scope.page = 1;
$scope.alertPage = function() {
alert($scope.page);
}
})
app.directive('incrementer', function() {
return {
scope: {
page: '=',
alertPage: '&'
},
template: '<button ng-click="incrementPage()">increment page</button>',
link: function(scope, elem, attrs) {
scope.incrementPage = function() {
scope.page += 1;
scope.alertPage();
}
}
}
})
html template:
<body ng-app='app' ng-controller='myCtrl'>
page is {{page}}
<incrementer page='page' alert-page='alertPage()'></incrementer>
</body>
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…