本文介绍了使用`这一点。$ watch`,而不是`$范围。$ watch`与“控制器”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我使用的是控制器格式作用域控制器。

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

}]);

我得到的不确定是不是这个没有一个方法 $观看参考$ C>。

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

推荐答案

即使在 controllerAs 格式的 $范围是存在的。

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

其实什么 controllerAs 确实是绑定控制器实例的这个到$范围。结果
例如。 控制器=作为myController的myctrl做(幕后): $ scope.myctrl =此(其中这个 myController的实例)。

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) {...});
});

这篇关于使用`这一点。$ watch`,而不是`$范围。$ watch`与“控制器”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 19:25
查看更多