如何将输入值输入到 Angular 的 $scope 中? [英] How do I get an input value into Angular's $scope?

查看:56
本文介绍了如何将输入值输入到 Angular 的 $scope 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Angular 的新手,我正在尝试做一些非常基础的事情.这是视图的一部分(所有角度文件都添加到别处):

 

<input type='text' ng-model='id'>

这是我的控制器:

 module.controller('ctrl',['$scope', function ($scope) {//在这里获取范围值}]);

我想做的很简单.我想使用输入值.我尝试了类似 $scope.data = []$scope.data.push($scope.id) 之类的东西来创建一个具有范围值的数组,但它没有不行.当我尝试显示该值时,控制台上显示未定义".

你们有什么想法吗?

该视图还有一个带有 ng-click 指令的按钮,该指令触发控制器的函数,我尝试获取我的值.

解决方案

该值将自动添加到 $scope,但您必须在 input 中键入一些内容> 元素.

也就是说,你需要触发一些东西来获得这个值.例如,你有你的评论 //get the scope value here -- 这在控制器初始化后立即触发并且不再被调用;所以,它会在那个时候记录 undefined .但是,如果您将其设置为单击按钮或其他方式,您将看到它可用:

<input type='text' ng-model='id'><button ng-click="logId()">日志 ID</button>

还有你的控制器:

module.controller('ctrl',['$scope', function ($scope) {$scope.logId = function() {控制台日志($scope.id);}}]);

现在在输入中输入一些内容并点击按钮.

I'm new to Angular, and I am trying to do something really basic. Here is a part of a view (all angular files are added elsewhere) :

 <div ng-controller='ctrl'>
    <input type='text' ng-model='id'>
 </div>

And here is my controller :

 module.controller('ctrl',['$scope', function ($scope) {

    // get the scope value here
}]);

What I'm trying to do is really simple. I'd like to use the input value. I tried something like $scope.data = [] and $scope.data.push($scope.id) to create an array with the scope's value, but it didn't work. When I tried to display the value, I got an 'undefined' on the console.

Do you guys have any idea ?

Edit : The view also has a button with the ng-click directive which trigger the controller's function where I try to get my value.

解决方案

The value will automatically be added to the $scope, but you have to type something into the input element.

That said, you need to trigger something to get this value. For example, where you have your comment // get the scope value here -- this is triggered as soon as the controller is initialized and never called again; so, it's going to log undefined at that time. However, if you set it to a button click, or something, you will see it's available:

<div ng-controller='ctrl'>
   <input type='text' ng-model='id'>
   <button ng-click="logId()">Log ID</button>
</div>

And your controller:

module.controller('ctrl',['$scope', function ($scope) {
    $scope.logId = function() {
        console.log($scope.id);
    }
}]);

Now type something into the input and click the button.

这篇关于如何将输入值输入到 Angular 的 $scope 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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