AngularJS手表无法正常工作

poa*_*oas 14 watch angularjs

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

<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>
Run Code Online (Sandbox Code Playgroud)

像这样:

<div ng-include src="filterPath" onload="initiateSearch()"></div>
Run Code Online (Sandbox Code Playgroud)

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
            });
        };
    }]);
})();
Run Code Online (Sandbox Code Playgroud)

一切似乎都没事了但是...当我开始输入名为searchKeyword的输入元素时,searchKeyword上的$ watch永远不会触发该函数.

Ant*_*rot 42

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

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

如果你对这是什么感到好奇true,这里是文档中的函数签名:

$watch(watchExpression, listener, [objectEquality]);
Run Code Online (Sandbox Code Playgroud)

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

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


Car*_*arl 35

手表必须是对象的属性,而不是对象本身,请参阅此示例 https://docs.angularjs.org/api/ng/type/ $ rootScope.Scope如何添加手表,以及使用这里的模型https://docs.angularjs.org/api/ng/directive/input.你可以试试这个(我还没试过)

data-ng-model="search.keyword"
Run Code Online (Sandbox Code Playgroud)

并在您的控制器中:

$scope.search = {}
Run Code Online (Sandbox Code Playgroud)

...

$scope.$watch('search.keyword', ... 
Run Code Online (Sandbox Code Playgroud)