使用 `this.$watch` 而不是 `$scope.$watch` 和 'Controller As' [英] Use `this.$watch` instead of `$scope.$watch` with 'Controller As'

查看:37
本文介绍了使用 `this.$watch` 而不是 `$scope.$watch` 和 'Controller As'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我使用 Controller As 格式来定义控制器.

这对于保持视图上的值范围清晰且易于遵循非常有用.

<ul><li ng-repeat="myctrl.contacts 中的联系人"><input type="text" ng-model="contact.name.first"/>

但是,在实现 $watch 时,我遇到了问题,因为它似乎依赖于 $scope,因此以下内容不起作用.

angular.module('myApp',[]).controller('myController',['contacts',function(contacts) {this.contacts = 联系人;this.$watch('contacts', function(newValue, oldValue) {控制台日志({旧:旧值,新:新值});});}]);

我得到 undefined is not a function 参考 this 没有方法 $watch.

有没有办法$watchController As 格式的值?

JS 小提琴

解决方案

即使使用 controllerAs 格式,$scope 也存在.

实际上 controllerAs 所做的是将控制器实例的 this 绑定到 $scope.
例如.controller="myController as myctrl" 做了(在幕后):$scope.myctrl = this(其中 this 指的是 myController 实例).

因此,您可以为手表注入并使用 $scope :

.controller('myController', function ($scope, contacts) {this.contacts = 联系人;$scope.$watch(function () {返回联系人;}, 函数 (newValue, oldValue) {...});});

Currently I am using the Controller As format for scoping controllers.

This works great for keeping the scope of values on the views clear and easy to follow.

<div ng-app="myApp" ng-controller="myController as myctrl">
    <ul>
        <li ng-repeat="contact in myctrl.contacts">
            <input type="text" ng-model="contact.name.first" />
        </li>
    </ul>
</div>

However, when implementing a $watch I am running into problems because it seems to be dependent on $scope so the following will not work.

angular.module('myApp',[])
.controller('myController',['contacts',function(contacts) {
    this.contacts = contacts;

    this.$watch('contacts', function(newValue, oldValue) {
       console.log({older: oldValue, newer:newValue});
    });

}]);

I get undefined is not a function in reference to this not having a method $watch.

Is there a way to $watch a value with the Controller As format?

JS Fiddle

解决方案

Even with the controllerAs format, the $scope is there.

In fact what controllerAs does is bind the controller instance's this to the $scope.
E.g. controller="myController as myctrl" does (behind the scenes): $scope.myctrl = this (where this refers to the myController instance).

So, you can just inject and use the $scope for watches:

.controller('myController', function ($scope, contacts) {
    this.contacts = contacts;

    $scope.$watch(function () {
        return contacts;
    }, function (newValue, oldValue) {...});
});

这篇关于使用 `this.$watch` 而不是 `$scope.$watch` 和 'Controller As'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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