在我的 angularjs 控制器中获取 ng-change 字段的值 [英] Getting value of ng-change field in my angularjs controller

查看:22
本文介绍了在我的 angularjs 控制器中获取 ng-change 字段的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为这一行:

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

}])

但这给了我未定义".

如何在控制器中引用 mySearch 输入字段的值?

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

推荐答案

您的输入字段可能位于未正确更新的单独范围内.ngIfng-repeat 是创建单独子作用域的指令的常见示例.(有关范围的更多信息,请参阅这篇文章)

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)

为了保护自己免受此类问题的影响,您可以将变量存储在对象中.

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

命名控制器

或者按照 angular 风格指南中的推荐命名你的控制器 Y030.

第三个选项是简单地将变量作为参数传递给函数:

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

这篇关于在我的 angularjs 控制器中获取 ng-change 字段的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆