0
votes

I am working on an AngularJs application and I have a confusing issue here when I am trying to watch on controller scope property within link function of a directive

Here is minimal example of the issue

HTML

<div  fc-loading="filterBox"></div>

controller

angular.module('myApp').controller('myctrl', function ($scope) {
   $scope.filterBox = false;
   setInterval(function () { 
    $scope.filterBox = !$scope.filterBox;
},2000)
}

Directive

angular.module('myApp').directive('fcLoading', function () {
return{
    scope:{
        fcLoading:'='
    },
    link: function (scope,ele,attrs) {
        scope.$watch(scope[attrs.fcLoading],function(newValue, oldValue){

            console.log(newValue)
        }
     }

Thanks in advance!

2
Please clarify: what variable are you trying to watch. Are you trying to watch the fcLoading variable, or are you trying to watch a variable with the name of whatever string is in attrs.fcLoading? - aaronofleonard
attrs.fcLoading is equivalent to filterBox which is the name of the property in the scope of controller $scope.filterBox I am using the attributes to just isolate the scope - Peter Wilson

2 Answers

2
votes

AngularJs Directive scope '=' method lets you to have 2 ways binding inside your directive, and you can only watch your directives scope variable.like this

scope.$watch('fcLoading', function(newValue, oldValue){
    console.log(newValue);
}, true)

By the way call $scope.$apply() inside setInterval function or use $interval

1
votes

You should be able to just watch the value that you're putting on the scope here:

scope:{
    fcLoading:'='
},

like this in your link function:

scope.$watch(scope.fcLoading, function(newValue, oldValue){
    console.log(newValue);
}