【问题标题】:add watch on a non scope variable in angularjs在angularjs中的非范围变量上添加监视
【发布时间】:2015-04-15 06:47:41
【问题描述】:

有没有办法将监视添加到非范围变量。我想在局部变量中添加一个手表。我有这样的东西

 function EditAssetRegistryController(assetregistryService, manufacturerService, assettypeService, projectService, $localStorage, $routeParams) {
        var vm = this;
        vm.manufacturers = [];
        vm.projects = [];
        vm.asset_types = [];
        vm.ch_group_uniq = 'none';
}

有没有办法将手表添加到 vm.ch_group_uniq? 我知道如何使用范围变量来完成它,但我有一些场景我必须检查许多复杂的变量。

【问题讨论】:

    标签: javascript angularjs angularjs-directive angularjs-scope


    【解决方案1】:

    好吧,您可以通过将函数作为第一个参数传递来轻松地为 anything 添加监视:

    $scope.$watch(function watchFunction(scope) {
        return vm.ch_group_uniq
    }, handler)
    

    需要考虑的几点:watchFunction 必须返回相同的值,如果没有任何变化。这可能会导致一些陷阱,例如,返回某些数组操作的结果:[1,2,3].filter(...) 将始终返回一个新数组,并导致无限的$digest 循环。还要注意$scope.$watch 的第三个参数,它指示是否使用标识比较,或angular.equals 比较值时。 (查看文档以获取更多信息 - https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$watch

    但是,您的具体问题似乎是尝试使用controllerAs 和自定义$watch-es。有一个非常方便的库专门解决了这个问题:https://github.com/christopherthielen/angular-360-no-scope

    【讨论】:

    • 很好的解决方案,但是当变量更改时它不会直接影响手表,除非当前范围内有任何其他更改。
    【解决方案2】:

    $watch 不能像普通语法一样使用controllerAs。你需要把它绑定到$scope,然后你就可以看那个变量了:

    代码

    $scope.$watch(angular.bind(this, function (ch_group_uniq) {
      return this.ch_group_uniq;
    }), function (newVal, oldVal) {
      console.log('Name changed to ' + newVal);
    });
    

    这里是参考Todd Motto Article

    【讨论】:

      【解决方案3】:

      使用 ES6 的更简洁的语法

      $scope.$watch(() => {
          return this.thingToWatch;
      }, (newVal, oldVal) => {
          // Your code here...
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多