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

查看:91
本文介绍了在我的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?

推荐答案

您的输入字段可能位于一个正确的范围内,该范围未正确更新。 ngIf ng-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);
}; 



命名控制器



或命名控制器专门按照角度样式指南 Y030 的建议进行操作

Named Controllers

Or name your controllers specifically as recommended in the angular style guide 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天全站免登陆