AngularJS $范围没有观察View的变化

时间:2016-02-18 14:18:01

标签: javascript angularjs binding controller watch

我有一个小样本,我希望在浏览器控制台中看到日志消息,表明$ scope观察者运行良好,但遗憾的是并非如此。

<!doctype html>
<html ng-app="demo">

<head>
    <script src="bower_components/angular/angular.js"></script>
    <script>
    var app = angular.module('demo', ['ng']);
    app.controller('demoCtrl', function($scope) {
        var self = this;

        self.searchText = '';
        $scope.$watch('self.searchText', function(n, p) {
            console.log('searchText changed from', n, 'to', p);
        });

    });
    </script>
</head>

<body ng-controller="demoCtrl as ctrl">
    <input type="text" ng-model="ctrl.searchText" />
</body>

</html>

4 个答案:

答案 0 :(得分:2)

您需要在ctrl中使用别名self(不是$scope.$watch(...)):

<!doctype html>
<html ng-app="demo">

<head>
    <script src="bower_components/angular/angular.js"></script>
    <script>
    var app = angular.module('demo', ['ng']);
    app.controller('demoCtrl', function($scope) {
        var self = this;

        self.searchText = '';
        $scope.$watch('ctrl.searchText', function(n, p) {
            console.log('searchText changed from', n, 'to', p);
        });

    });
    </script>
</head>

<body ng-controller="demoCtrl as ctrl">
    <input type="text" ng-model="ctrl.searchText" />
</body>

</html>

当使用ng-controller="demoCtrl as ctrl"时,Angular会在范围内创建指向控制器上下文对象this的链接:$scope.ctrl

答案 1 :(得分:1)

将您的$watch更改为:

$scope.$watch(function() {
    return self.searchText;
  }, function(n, p) {
    console.log('searchText changed from', n, 'to', p);
  });

答案 2 :(得分:1)

form you used $scope.$watch中,观看表达式应该是范围或根范围的一部分。 所以你应该改变你的代码:

<!doctype html>
<html ng-app="demo">

<head>
    <script src="bower_components/angular/angular.js"></script>
    <script>
    var app = angular.module('demo', ['ng']);
    app.controller('demoCtrl', function($scope) {
        var self = this;

        $scope.searchText = '';
        $scope.$watch('searchText', function(n, p) {
            console.log('searchText changed from', n, 'to', p);
        });

    });
    </script>
</head>

<body ng-controller="demoCtrl as ctrl">
    <input type="text" ng-model="searchText" />
</body>

</html>

或使用其他表单并更改您的代码:

    

<head>
    <script src="bower_components/angular/angular.js"></script>
    <script>
    var app = angular.module('demo', ['ng']);
    app.controller('demoCtrl', function($scope) {
        var self = this;

        self.searchText = '';
        $scope.$watch(function() { return self.searchText; }, function(n, p) {
            console.log('searchText changed from', n, 'to', p);
        });

    });
    </script>
</head>

<body ng-controller="demoCtrl as ctrl">
    <input type="text" ng-model="ctrl.searchText" />
</body>

</html>

答案 3 :(得分:0)

答案很简单 -

Angular监视范围变量而不是控制器实例上的表达式。

要使代码工作,您需要修改控制器代码,如下所示

var self = this;

self.searchText = '';
$scope.self = this;
$scope.$watch('self.searchText', function(n, p) {
console.log('searchText changed from', n, 'to', p);
});