AngularJS $ rootScope函数ng-change

时间:2014-08-06 13:51:25

标签: javascript angularjs angularjs-scope

HTML

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

上面是一个输入字段,用作实时搜索,将其放入index.html并使用Angular-Route我正在使用路由来加载页面。

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

    });

我见过的ng-change()函数应该在.run()内,但是当我按键时,仍然没有console.log()返回。

我如何能够运行ng-change或ng-click from the $ rootScope?

1 个答案:

答案 0 :(得分:2)

ng-change接受一个参数,这是一个表达式。一旦输入值发生变化,表达式将在当前范围的上下文中进行评估。这意味着,如果与当前元素(或其任何其他父作用域)关联的作用域不具有$rootScope属性,则您的代码段将起作用。

尝试这样的事情:

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