<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js@1.5.8" data-semver="1.5.8" src="https://code.angularjs.org/1.5.8/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
<title>Directive Callbacks</title>
</head>
<body ng-app="myApp" ng-controller="Controller">
<h1>Directive with Callback Example</h1>
<h3>Open the console in your web browser.</h3>
<clicker new-value="clickersValue" my-update="clickersCallback()"></clicker>
<p>
Clicker's value is the initialized value when the callback is invoked: <strong> {{clickersValueRightAfterCall}}</strong>
</p>
<p>
But eventually it becomes: <strong> {{clickersValue}}</strong>
</p>
<script>
var app = angular.module('myApp', []);
app.controller('Controller', ['$scope',
function($scope) {
// initialize the value to something obvious
$scope.clickersValue = "BEFORE";
// when this call back is called we would expect the value to be updated by updated by the directive
$scope.clickersCallback = function() {
//$scope.$apply(); // $apply is not allowed here
$scope.clickersValueRightAfterCall = $scope.clickersValue;
console.log("clickersCallback: scope.clickersValue", $scope.clickersValue);
};
}
]);
app.directive('clicker', [function() {
return {
restrict: 'EA',
template: '<div ng-click="clicked()">click me!</div>',
controller: ['$scope', '$timeout', function($scope, $timeout) {
$scope.clicked = function() {
console.log("you clicked me.");
$scope.newValue = 'VALID';
$timeout(function() {
$scope.myUpdate();
});
}
}],
scope: {
"newValue": "=",
"myUpdate": "&"
}
};
}]);
</script>
</body>
</html>
// Code goes here
/* Styles go here */
This Plunker shows an example of scope variables not being updated when the callback is invoked.