Search code examples
javascriptangularjs-directiveangularjs-scopeangularjs-service

angularjs: using $watch in directive to call serivce


I am creating a directive that does a two day binding with an input box.

a $watch is placed inside link function(which i don't know if this is a good idea) to watch the value in the input box.

it looks like the scope.$watch is not doing anything at all.

I can't figure out what the problem is as i have tried to replace from

scope.$watch('var',srv.doStuff(),true);

to

scope.$watch('location',srv.doStuff(),true);

No luck still.

Thanks all

http://plnkr.co/edit/4XUqPsCLFOoJD0BPlk14

index.html

<div ng-controller="formCtrl">
<form novalidate class="simple-form">
    Input: <input type="text" ng-model="location" required><br/>
</form>
<div ng-mydir var="location"></div>
<div>

app.js

var app = angular.module('plunker', []);

app.controller('formCtrl', function($scope) {
  $scope.location="empty";
});

// a service 
app.service('srv', function() {
  //a function does stuff
  this.doStuff=function (){
     console.log('i am done');
  };
});


//a diretive calls serivce
app.directive('ngMydir', function (srv) {
  return {
    restrict: 'A',
    scope: {
        var:'='
    },
    link: function(scope,elem,attrs,ctrl){
    console.log(scope.var);
    scope.$watch('var',srv.doStuff(),true);
    }
  };
});

Solution

  • You passed in srv.doStuff(), which is a function call rather than an actually function, you can use one of the following solutions:

    Warp the function call srv.doStuff() in a function like this

    link: function (scope, elem, attrs, ctrl) {
        scope.$watch('var', function () {
            srv.doStuff();
        }, true);
    }
    

    Or simply

    link: function (scope, elem, attrs, ctrl) {
        scope.$watch('var', srv.doStuff, true);
    }