I have a simple button directive that notifies the controller when the button is clicked. However I do not understand why I need to add $scope.$digest() in order for the action to update the scope. See code:
var myModule = angular.module("myModule", []);
myModule.directive("myDirective", function() {
return {
restrict: "A",
scope: {
action: "&"
},
link: function(scope, element, attrs) {
element.bind("click", function() {
scope.action();
});
}
};
});
myModule.controller("TestCtrl", function($scope) {
$scope.divShow = false;
$scope.buttonClick = function() {
$scope.divShow = !$scope.divShow;
// why is this needed?
$scope.$digest();
}
});
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myModule">
<div ng-controller="TestCtrl">
<button my-directive action="buttonClick()">Click</button>
<div ng-show="divShow">
Div is shown
</div>
</div>
</body>
</html>
Here's a jsfiddle