简体   繁体   English

控制器中的Ng模型未定义

[英]Ng-model undefined in the controller

I am having some "problems" reading an ng-model from the controller. 我有一些“问题”从控制器读取ng模型。

I want to do this: 我想做这个:

<input type="text" ng-model="code">
<button ng-click="setCode()">Login</button>

And in my controller access that variable like this: 并在我的控制器访问该变量,如下所示:

 $scope.setCode = function(){
    alert($scope.code);
  }

That is what I want to do but my code variable is undefined. 这就是我想要做的,但我的代码变量是未定义的。

I found 2 ways to get this to work: 我找到了两种方法来实现这个目的:

1) Passing the variable as an argument 1)将变量作为参数传递

<input type="text" ng-model="code">
<button ng-click="setCode(code)">Login</button>

and: 和:

$scope.setCode = function(code){
    alert(code);
  }

2) Declaring my variable as an object 2)将变量声明为对象

<input type="text" ng-model="code.text">
<button ng-click="setCode()">Login</button>

and: 和:

$scope.code = {text: 'foo'};

[...]

$scope.setCode = function(){
    console.log($scope.code);
  }

(I prefer the second one) (我更喜欢第二个)

But I am a little confused about what I should do. 但我对我应该做的事情感到有点困惑。 It's ok to declare my ng-models like objects? 可以将我的ng模型声明为对象吗? I have to declare ALL my models like objects? 我必须声明我的所有模型都像对象?


EDIT: Here is a Plnkr of the problem 编辑: 这是一个问题的Plnkr

In this example (I am using the Ionic framework), I declare a variable code with the value test, when I change the model in the input and press the Start button, in theory I have to see in an alert the new value of the model. 在这个例子中(我正在使用Ionic框架),我声明了一个带有值test的变量代码,当我在输入中更改模型并按下Start按钮时,理论上我必须在警报中看到新的值模型。 But what I see is the old one. 但我看到的是旧的。

Thanks! 谢谢!

I fixed your plnkr example using object model instead of primitive type. 我使用对象模型而不是基本类型修复了plnkr示例。

$scope.model = {};
$scope.model.code = "test";

$scope.setCode = function(){
    alert($scope.model.code);
}

See the plnkr . plnkr

Your first example is working, here is a plunkr . 你的第一个例子是工作, 这是一个plunkr

If you hit the button without entering any text into the input field you get an alert undefined . 如果按下按钮而未在输入字段中输入任何文本,则会收到undefined的警报。 $scope.code gets defined the moment you enter something to its bound field ng-model="code" . $scope.code在您向其绑定字段ng-model="code"输入$scope.code时定义。

You could initialize it to a default in your controller too: 您也可以将其初始化为控制器中的默认值:

$scope.code = 'my default value';

Ionic的指令将创建新范围,如果要直接在控制器中使用代码对象,则必须将ng-controller设置为HTML页面中的离子内容,而不是路由器状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM