简体   繁体   English

为什么scope。$ watch无法正常工作?

[英]why scope.$watch is not working?

I have angularjs directive with template which consists of two tags - input and the empty list. 我有带有模板的angularjs指令,该指令由两个标签组成-输入和空列表。 What I want is to watch input value of the first input tag. 我要看的是第一个输入标签的输入值。 The $watch() method is called once when directive is initialised but that's it. 初始化指令后,将立即调用$watch()方法,仅此而已。 Any change of input value is silent. 输入值的任何更改都是静默的。 What do I miss? 我想念什么?

here is my plunk 这是我的朋克

and here is the code: 这是代码:

.directive('drpdwn', function(){
   var ref = new Firebase("https://sagavera.firebaseio.com/countries");

function link(scope, element, attrs){

  function watched(){
    element[0].firstChild.value = 'bumba'; //this gets called once
    return element[0].firstChild.value;
  }

  scope.$watch(watched, function(val){
    console.log("watched", val)
  }, true);

}
return {
  scope:{
    searchString: '='
  },
  link: link,
  templateUrl:'drpdwn.html'
}
})

Edit: 编辑:

if I call $interval() within link function it works as expected. 如果我在链接函数中调用$interval() ,它将按预期工作。 is this intentional behaviour? 这是故意行为吗?

It doesn't get called because there is never a digest triggered on the scope. 它不会被调用,因为示波器上永远不会触发摘要。

Try this instead, using ng-model: 改用ng-model尝试一下:

http://plnkr.co/edit/qMP5NDEMYjXfYsoJtneL?p=preview http://plnkr.co/edit/qMP5NDEMYjXfYsoJtneL?p=preview

function link(scope, element, attrs){
  scope.searchString = 'bumba';
  scope.$watch('searchString', function(val){
    console.log("watched", val)
    val = val.toLowerCase();
    val = val.replace(/ */g,'');
    var regex = /^[a-z]*$/g;
    if (regex.test(val)) {
      scope.searchString = val;
      // TODO something....
    }
  }, true);

Template: 模板:

<input class="form-control"  ng-model="searchString" id="focusedInput"  type="text" placeholder="something" />
<div></div>

You are setting the the value you want in the watcher function. 您正在观察者功能中设置所需的值。

function watched(){
    element[0].firstChild.value = 'bumba'; //this gets called once
    return element[0].firstChild.value;
}

is essentially the same return value as 本质上与返回值相同

function watched() {
    return 'bumba';
}

So the watcher will always return the same value. 因此,观察者将始终返回相同的值。

If you want to initialize the value. 如果要初始化值。 Do it outside of the watcher: 在观察者外部执行此操作:

element[0].firstChild.value = 'bumba'; //this gets called once
function watched(){
    return element[0].firstChild.value;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM