poashoas poashoas - 8 months ago 99
AngularJS Question

AngularJS watch not working

A watch is not working.
I ng-include the following content:

<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>

like this:

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

The onload function is doing this:

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 = '',

$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

Everything seems to go allright but... the $watch on searchKeyword never fires the function when I start typing in the input element called searchKeyword.


The watch has to be an attribute of the object, not the object itself, see the example here https://docs.angularjs.org/api/ng/type/$rootScope.Scope on how to add a watch, and the use of the model here https://docs.angularjs.org/api/ng/directive/input. You could try this (I have not tested it)


and in your controller:

$scope.search = {}


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