【发布时间】:2014-12-10 20:59:11
【问题描述】:
手表不工作。 我ng-包括以下内容:
<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 永远不会触发该功能。
【问题讨论】:
-
把
watch放在控制器里面而不是initiateSearch里面 -
onload应该在<div>上做什么?特别是因为它试图调用角度范围内的方法。在控制器中调用你的方法 -
为什么要注入$rootScope?您是否在某处使用它,但您已从代码示例中删除了该部分?我通常会尽量避免使用 $rootScope ,除非别无选择,但通常总会有更好的解决方案。这个 IMO 不是您问题的根源,只是好奇。
-
当模板的 ng-include 完成加载时,onload 正在调用控制器内部的方法。当它准备好时,带有 ng-model="searchKeyword" 的元素就会存在。然后我想应用 $scope.$watch('searchKeyword', function(){})。问题是它在 $scope.initiateSearch = function () {} 内。将手表放在范围功能之外使其再次工作