为什么范围。$ watch不工作?

时间:2015-02-05 10:56:48

标签: javascript angularjs

我有一个带有模板的angularjs指令,它由两个标签组成 - 输入和空列表。我想要的是观察第一个输入标签的输入值。初始化指令时会调用$watch()方法,但就是这样。输入值的任何变化都是静默的。我错过了什么?

这是我的plunk

这是代码:

.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(),它会按预期工作。这是故意的行为吗?

2 个答案:

答案 0 :(得分:1)

它没有被调用,因为范围上从未触发过摘要。

请尝试使用ng-model:

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>

答案 1 :(得分:0)

您正在观察器功能中设置所需的值。

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;
}
相关问题