AngularJS手表无法正常工作

时间:2014-10-15 17:21:54

标签: angularjs watch

手表无法使用。 我包括以下内容:

<form class="search">
    <div class="searchbar">
        <input type="search" value="" data-ng-model="searchKeyword" placeholder="zoeken">
        <button type="submit"><i class="glyphicon glyphicon-search"></i></button>
    </div>
</form>
像这样:

<div ng-include src="filterPath" onload="initiateSearch()"></div>

onload函数正在执行此操作:

(function(){
    var appController = angular.module('ListerAppController', []);

    appController.controller('ListerCtrl', ['$scope', '$rootScope', '$http', '$filter', '$timeout', '$sharedFactories', 'History', '$location',
        function($scope, $rootScope, $http, $filter, $timeout, $sharedFactories, History, $location) {
            $scope.initiateSearch = function () {
            // This is what you will bind the filter to
                $scope.filterText = '';

                // Instantiate these variables outside the watch
                var tempFilterText = '',
                    filterTextTimeout;

                $scope.$watch('searchKeyword', function (val) {
                    if (filterTextTimeout) $timeout.cancel(filterTextTimeout);

                    tempFilterText = val;

                    filterTextTimeout = $timeout(function() {
                        $scope.filterText = tempFilterText;
                        $scope.pageCount = function() {
                            return Math.ceil( $scope.itemsfiltered.length / $scope.itemsPerPage );
                    };
                }, 350); // delay 250 ms
            });
        };
    }]);
})();

似乎所有事情都没有问题但是...当我开始输入名为searchKeyword的输入元素时,searchKeyword上的$ watch永远不会触发该函数。

4 个答案:

答案 0 :(得分:42)

您是否尝试添加true,如下所示?

$scope.$watch('searchKeyword', function (val) {
 /* your logic here */                    
}, true);

如果您对true的内容感到好奇,请点击the docs中的函数签名:

$watch(watchExpression, listener, [objectEquality]);
  

当objectEquality == true时,watchExpression的不等式根据angular.equals函数确定。要保存对象的值以供以后比较,请使用angular.copy函数。因此,这意味着观看复杂的物体会对记忆和性能产生不利影响。

显然,重要的是它以不同的方式检查旧值和新值的相等性。我可以看到这是必要的,如果(如果我错了,请纠正我)你正在观看的价值是,例如,数组而不是字符串。

答案 1 :(得分:33)

手表必须是对象的属性,而不是对象本身,请参阅此处的示例https://docs.angularjs.org/api/ng/type/ $ rootScope.Scope如何添加手表,并在此处使用模型{{3} }。 你可以尝试这个(我还没有测试过)

data-ng-model="search.keyword"

并在您的控制器中:

$scope.search = {}

...

$scope.$watch('search.keyword', ... 

答案 2 :(得分:1)

只需添加可能的解决方案列表:

使用表格时:

使用ng-pattern将调用$ watch的调用,除非并且直到输入被ng-pattern验证。

所以,以防万一有人使用ng-pattern,请在删除ng-pattern后尝试$ watch。

更多阅读:

Angular.js - ng-change not firing when ng-pattern is $invalid

答案 3 :(得分:0)

最简单的一个是传递true作为$ watch的最后一个参数。

更多阅读:

https://github.com/mbenford/ngTagsInput/issues/174