javascript - angularjs: using $watch in directive to call serivce -
i creating directive 2 day binding input box.
a $watch placed inside link function(which don't know if idea) watch value in input box.
it looks scope.$watch not doing @ all.
i can't figure out problem have tried 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"; }); // service app.service('srv', function() { //a function stuff this.dostuff=function (){ console.log('i 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); } }; });
you passed in srv.dostuff()
, function call rather function, can use 1 of following solutions:
warp function call srv.dostuff()
in function 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); }
Comments
Post a Comment