I've stumbled upon an Angular issue that I just don't understand or know how to solve the problem.
I'd like to have a callback function located in a controller that a directive calls once something is done. The directive first alters some scope variable and runs the callback. The callback function then proceeds to do something with that same scope variable. This might seem confusing as why I'd want this but consider that the directive is generic and handles many different cases whereas the callback is a very specific function. It's important to note I CANNOT pass this variable as an argument as other code will need use of this scope variable as well.
Now onto the problem. I have everything working up til the callback is executed. It seems within the callback, the variable has yet to change. However, if a timeout is set (in my example, a single second) the variable is recognized as changed. Why does it have this behavior? Even in the directive before the callback is called, it shows that the variable is in fact changed. I've created a Codepen that demonstrates this issue. It simply toggles the button label from 'A' to 'B'. You'll notice though in the console log that when the variable is printed in the callback it is the 'old' value until I have waited.
Any info would be awesome, thanks!
NOTE: An idea I thought of was saving a copy of the scope variable as a local variable in the directive, and sending that local variable as an argument to the callback since the callback is currently the only function i care about that immediately knows the change of the variable and acts upon it.
Codepen: http://codepen.io/anon/pen/KayaRW
HTML:
<div ng-app="myApp" ng-controller="myCtrl">
<div ng-test="" button-label="myLabel" callback="cbFunc()">
</div>
</div>
JS:
angular
.module('myApp', [])
.controller('myCtrl', function($scope) {
$scope.myLabel = "A";
$scope.cbFunc = function() {
console.log("myLabel in callback: " + $scope.myLabel);
setTimeout(function() {
console.log("myLabel in callback, after 1 sec: " + $scope.myLabel);
console.log("");
}, 1000);
}
}).directive('ngTest', function() {
return {
scope: {
buttonLabel: '=',
callback: '&'
},
template: function(element, attrs) {
element.html("<button class=\"btn\" ng-click=\"changeLabel()\">Button Label: {{buttonLabel}}</button>");
},
link: function($scope, $element, $attrs) {
$scope.changeLabel = function() {
if ($scope.buttonLabel == "A") {
$scope.buttonLabel = "B";
} else {
$scope.buttonLabel = "A";
}
console.log("myLabel before callback: "+ $scope.buttonLabel);
$scope.callback();
}
}
}
});