为什么范围$手表坏了

why scope.$watch is not working?

本文关键字:坏了 手表 范围 为什么      更新时间:2023-09-26

我有angularjs指令和模板,它由两个标签组成——input和空列表。我想要的是观察第一个输入标签的输入值。当指令初始化时,$watch()方法被调用一次,但仅此而已。输入值的任何更改都是静默的。我想念什么?

这是我的垃圾

这是代码:

.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'
}
})

编辑:

如果我在链接函数中调用$interval(),它将按预期工作。这是故意的行为吗?

它不会被调用,因为从来没有在作用域上触发过摘要。

试试这个,使用ng模型:

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

模板:

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

您正在观察程序函数中设置所需的值。

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

与的返回值基本相同

function watched() {
    return 'bumba';
}

因此,观察者将始终返回相同的值。

如果要初始化该值。在观察者之外做:

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