簡體   English   中英

angularjs:使用$ watch in directive來調用serivce

[英]angularjs: using $watch in directive to call serivce

我正在創建一個使用輸入框進行兩天綁定的指令。

一個$ watch被放置在鏈接函數內(我不知道這是不是一個好主意)來觀察輸入框中的值。

看起來像是范圍。$ watch根本沒有做任何事情。

我無法弄清楚我試圖替換的問題是什么

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

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

還沒有運氣。

謝謝大家

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);
    }
  };
});

您傳入的是srv.doStuff() ,它是一個函數調用而不是實際函數,您可以使用以下解決方案之一:

在這樣的函數中扭曲函數調用srv.doStuff()

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

或者干脆

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM