Lets say I have a controller & directive like so:
app.controller('mainController', function($scope) {
$scope.loading = true;
$scope.updateTest = function(){
$scope.loading = false;
}
}).directive('loading', function() {
return {
restrict : 'E',
transclude: true, // use parent scope
link : function(scope, element, attrs) {
scope.$watch('loading', function(ctx) {
console.log('updating?', ctx)
});
}
}
});
And a html markup:
<section ng-controller="mainController">
<loading ng-show="loading">
loading?
</loading>
<button ng-click="updateTest()">Force update</button>
</section>
I just want to know how to watch the parent scope from within a directive, I can't seem to get this working!
I'm using Angular 1.3.16
I recommend you to use isolate scope like this and pass all variables throw it:
.directive('loading', function() {
return {
restrict : 'E',
scope: {
ngModel: '='
},
transclude: true, // use parent scope
link : function(scope, element, attrs) {
scope.$watch('ngModel', function(ctx) {
console.log('updating?', ctx)
});
}
}
});
Html
<loader ng-model="loading" ng-show="loading">
loading?
</loader>