$watch 不会触发数据更改 [英] $watch not firing on data change

查看:54
本文介绍了$watch 不会触发数据更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个针对 ui-select2 下拉列表模型的手表设置(来自 ui-bootstrap).手表在加载时触发,但不会在数据更改时触发,我不知道为什么.

不应用模型更改或不使用第三个参数进行相等比较(至少从我的代码来看)不是常见的问题.

我需要做什么才能让它启动?

这里有一个 plunk 演示了这个问题.

解决方案

我修复了一些问题.

http://plnkr.co/edit/5Zaln7QT2gETVcGiMdoW?p=preview

JS

var myMod = angular.module("myApp",[]).controller("MainController", function($scope){$scope.myModel = {selectedId:null};}).controller("DetailController",function($scope){$scope.items = [1,2,3,4];$scope.watchHitCount = 0;$scope.$watch('myModel.selectedId', function(newVal, oldVal){console.log(newVal + " " + oldVal);$scope.watchHitCount++;},真的);});

index.html

 <div ng-controller="MainController"><ng-include src="'detail.html'" ng-controller="DetailController"></ng-include>

detail.html

观看命中:{{watchHitCount}}</pre><pre>选择的值:{{myModel.selectedId}}</pre><select ng-model="myModel.selectedId" ui-select2=""><选项></选项><option ng-repeat="item in items" value="{{item}}">{{item}}</option></选择>

它抱怨找不到控制器,所以我按照通常的方式使用命名的 ng-app 和一个声明了控制器的模块进行了设置.

我还添加了一个对象来保存模型中的值.使用 $scope 对象作为模型是不好的做法,而您的作用域应该引用作为模型的对象.

I have a watch setup against the model of a ui-select2 dropdown (from ui-bootstrap). The watch fires on load but not on data changes and I can't figure out why.

It isn't the usual problem of not $apply'ing the model change or not using the third parameter for equality comparison (at least from my code).

What do I need to do to get it to fire?

Here is a plunk demonstrating the issue.

解决方案

I fixed some stuff.

http://plnkr.co/edit/5Zaln7QT2gETVcGiMdoW?p=preview

The JS

var myMod = angular.module("myApp",[]).controller("MainController",  function($scope){
  $scope.myModel = {selectedId:null};
}).controller("DetailController",function($scope){
  $scope.items = [1,2,3,4];

  $scope.watchHitCount = 0;
  $scope.$watch('myModel.selectedId', function(newVal, oldVal){
    console.log(newVal + " " + oldVal);
    $scope.watchHitCount++;
  },true);
});

The index.html

  <body ng-app="myApp">
    <div ng-controller="MainController">
      <ng-include src="'detail.html'" ng-controller="DetailController"></ng-include>
    </div>
  </body>

The detail.html

<pre>watch hit: {{watchHitCount}}</pre>
<pre>selected value: {{myModel.selectedId}}</pre>
<select ng-model="myModel.selectedId" ui-select2="">
  <option></option>
  <option ng-repeat="item in items" value="{{item}}">{{item}}</option>
</select>

It was complaining about not finding the controller so I set it up the way I normally would with a named ng-app and a module declared that has controllers defined on it.

I also added an object to hold the value in your model. It is bad practice to use the $scope object as your model, instead your scope should refer to an object that is your model.

这篇关于$watch 不会触发数据更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆