0

I have declared a variable in parent scope in one of my controllers.

$scope.myValue = true;

This value is fetched in the custom directive easily. But when the value is updated in the parent controller it is not reflected in the custom directive.

My question is how can we let the directive know that the "myValue" is changed?

If the info is not suffice kindly let me know.

4
  • 1
    create a service, add this variable to that service, inject this service into controller as well as directive and there you go Commented Mar 31, 2015 at 10:56
  • 1
    Can't you $watch it inside the directive? Commented Mar 31, 2015 at 10:57
  • @SergiuParaschiv tried $watch. But it is called only once. ie., when view is loaded. Commented Mar 31, 2015 at 10:58
  • Then it probably means you are overwriting the reference you are $watching or are not $applying (through some built-in AngularJS directive like ng-click or manually) when you change it in the parent scope. Commented Mar 31, 2015 at 11:04

2 Answers 2

1

In your parent controller, upon changing the value of the variable, you can broadcast an event like this -

$scope.$broadcast('valueChanged', {
     val: $scope.myValue // pass in any object you want
});

And then in your child controllers, handle it like -

$scope.$on('valueChanged', function (event, data) {
     console.log(data); // get the same object here
});

$broadcast fires the event down, so this should work in your case.

Sign up to request clarification or add additional context in comments.

Comments

1

You can watch the value inside the directive, like this:

app.directive('directive', function() {
    return {
        scope: true,
        link: function($scope){
            $scope.$watch('$parent.myValue', function(newVal){
                console.log(newVal);
            });
        }
    };
});

Link demo: https://jsfiddle.net/mzrja04L/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.