简体   繁体   English

AngularJS-控制器中未定义的ng-model

[英]AngularJS - ng-model undefined in the controller

I am trying to read ng-model from the controller, however I could not get it work. 我正在尝试从控制器读取ng-model,但是无法正常工作。 It says the ng-model is undefined. 它说ng模型是未定义的。 I tried to apply the solution provided by others to solve this similar problem but I still could not get it work. 我尝试应用其他人提供的解决方案来解决此类似问题,但仍然无法正常工作。 Maybe because I am doing it wrongly. 可能是因为我做错了。

I have the following code snippet: 我有以下代码片段:

 var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.apply = function() { $scope.name = {} var firstName = $scope.name.FirstName; alert(firstName); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <div ng-app="myApp" ng-controller="myCtrl"> <button ng-click="apply()" type="button">Apply</button> Name: <input ng-model="name.FirstName"> </div> 

However, the alert says the variable "firstName" is undefined after clicking the "apply" button. 但是,警报显示,单击“应用”按钮后,变量“名字”未定义。 So I tried to use the following code instead. 因此,我尝试使用以下代码代替。

 var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.apply = function() { var theFirstname = ""; $scope.name = { theFirstname: $scope.name.FirstName } alert(theFirstname); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <div ng-app="myApp" ng-controller="myCtrl"> <button ng-click="apply()" type="button">Apply</button> Name: <input ng-model="name.FirstName"> </div> 

However, it seems like I am unable to assign $scope.name.FirstName to the variable "theFirstname". 但是,似乎我无法将$scope.name.FirstName分配给变量“ theFirstname”。

Move the initialization of name above apply() . name的初始化移到apply()上方。

By doing this, name.FirstName can be initialized from the Template as name is already defined on scope. 通过这样做,可以在模板中初始化name.FirstName ,因为已经在范围上定义了name

In your case, $scope.name={} is defined in the handler, thus name is undefined by the time when ng-model is attached to the textbox. 在您的情况下, $scope.name={}是在处理程序中定义的,因此在ng-model附加到文本框时, nameundefined的。

 var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { // Define the `name` object $scope.name = {}; $scope.apply = function() { var firstName = $scope.name.FirstName; console.log(firstName); }; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <div ng-app="myApp" ng-controller="myCtrl"> <button ng-click="apply()" type="button">Apply</button> Name: <input ng-model="name.FirstName"> </div> 

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

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