Angular: $watch for services inside directives problem
http://angularjs.org/
by maxisam
HTML
<script src="http://code.angularjs.org/angular-1.0.0.min.js"></script>
<div ng-controller="MyCtrl">
<button ng-click=change()>change state (look at log)</button>
<my-widget flag="myWidgetService.someState"></my-wigdet>
</div>
JavaScript
var myApp = angular.module('myApp',[]);
function MyCtrl($scope, myWidgetService) {
$scope.myWidgetService = myWidgetService;
$scope.change = function(){
myWidgetService.change();
}
}
myApp.factory('myWidgetService', function (){
var service= {};
service.someState = false;
service.change = function(){
service.someState = !service.someState;
console.log('state changed '+service.someState);
};
return service
});
myApp.directive('myWidget', function(myWidgetService) {
return {
restrict: 'E',
scope: {flag:'='},
replace: true,
transclude: true,
template:
'<div>'+
'<span> super widget</span>'+
'<div class="body" ng-transclude></div>'+
'</div>',
link: function($scope, elm, attrs, ctrl) {
$scope.$watch('flag' ,function(){
//this never fires why?
console.log('this never fires on state change');
}, true);
$scope.$watch('service',function(){
// is this the only way to bind this?
console.log('This fires as there is a binding from the scope');
},true);
}
}
});