简体   繁体   中英

AngularJS $rootScope function ng-change

html

<input type="text" data-search="type" placeholder="Search a Candidate, Job, Certificate or Location" ng-model="searchMain" ng-change="$root.updateSearchField(searchMain)"/>

Above is an input field that will act as a realtime search, this is put into index.html and using Angular-Route I am using routing for the pages to load in.

Angular

app.run(function($rootScope, $templateCache) {

        $rootScope.$on('$routeChangeStart', function(event, next, current) {
            console.log(current);
            if (typeof(current) !== 'undefined'){
                $templateCache.remove(current.templateUrl);
            }
        });

        $scope.filterText = '';
        // Instantiate these variables outside the watch
        var tempFilterText = '', filterTextTimeout;
        $rootScope.updateSearchField = function(foo) {
            console.log($scope.searchMain);
            if (filterTextTimeout) $timeout.cancel(filterTextTimeout);
            tempFilterText = foo;
            filterTextTimeout = $timeout(function() {
                $rootScope.searchText = tempFilterText;
                console.log($rootScope.searchText);
            }, 250); // delay 250 ms
        };

    });

The function for the ng-change() I've seen should be inside .run() and yet when I key up there is still no console.log() return.

How would I be able to run an ng-change or ng-click from the $rootScope`?

ng-change accepts a parameter, which is an expression. Once the value of the input changes the expression will be evaluated in the context of the current scope . This means that if the scope associated with the current element (or any other of its parent scopes), doesn't has $rootScope property, your snippet is not going to work.

Try something like this instead:

<input type="text" data-search="type" placeholder="Search a Candidate, Job, Certificate or Location" ng-model="searchMain" ng-change="updateSearchField()"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM