Getting value of ng-change field in my angularjs controller

霸气de小男生 提交于 2019-12-11 02:24:22

问题


I have this line in my view:

<input placeholder="Search" type="text" ng-change="searchChange()" ng-model="mySearch" ng-model-options="{debounce: 1000}">

And then inside my controller I have:

angular.module('app.controllers', [])

.controller('listViewCtrl', ['$scope', '$stateParams', '$http',
function ($scope, $stateParams, $http) {

    $http.get('http://www.domain.co.uk/api/search.php').
        then(function(response) {
            $scope.food = response.data;
        });

    $scope.searchChange = function() {
        console.log($scope.mySearch);   
    };         

}])

But this is giving me "undefined".

How can I reference the value of the mySearch input field in my controller?


回答1:


Your input field might be located within a sperate scope, which is not updated correctly. ngIf and ng-repeat are common examples for directives creating a separate sub-scope. (See this article for more information around scopes)

Dotted scope variables

To protect yourself from such issues you might either store your variables inside objects.

<input placeholder="Search" type="text" ng-change="searchChange()" ng-model="my.search" ng-model-options="{debounce: 1000}">


$scope.my = {search: ""};
$scope.searchChange = function() {  
    console.log($scope.my.search);
}; 

Named Controllers

Or name your controllers specifically as recommended in the angular style guide Y030.

Pass variable as parameter

A third option is simply passing the variable as parameter to the function:

<input placeholder="Search" type="text" ng-change="searchChange(mySearch)" ng-model="mySearch" ng-model-options="{debounce: 1000}">



$scope.searchChange = function(mySearch) {  
    console.log(mySearch);
}; 


来源:https://stackoverflow.com/questions/39616573/getting-value-of-ng-change-field-in-my-angularjs-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!