There is an issue with a directive that has a model and callback mapped to the parent scope. The problem arises when the parent model is updated after the callback has occurred, even though in the code it is assigned before.
DEMO: PLUNKER (Click twice or more and you will see that the model is updating after the click callback)
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.test = true;
$scope.test2 = true;
$scope.triggerCallback = function()
{
$scope.test2 = $scope.test;//it always see previous value here
};
}).directive('testdirective', [function () {
return {
restrict: 'A',
template: '<span ng-click="clicked()">from directive: {{checked}}</span>',
replace: true,
scope: {
bindModel: '=ngModel',
clickCallback: '&onClick'
},
link: function (scope, element) {
scope.checked = scope.bindModel;
scope.clicked = function () {
scope.checked = !scope.checked;
scope.bindModel = scope.checked;//MODEL UPDATE
//callback is called AFTER model updating, but model is updated after that
if (scope.clickCallback != undefined)
scope.clickCallback();
};
}
}
}]);
html:
<body ng-controller="MainCtrl">
<a href="">
<div testdirective ng-model="test" on-click="triggerCallback()"></div>
</a>
<br/>
<span>{{test2}}</span>
</body>
Although a workaround can be implemented by passing the new value in the callback function, in certain situations it may not be sufficient. Therefore, a more straightforward resolution is desired.