刚刚得到一个代码,看到代码正在工作,但在ng-model作者使用user.name或user.email等但这些属性永远不会在控制器中声明………那么它是如何工作的?
我们如何以这种方式将用户信息传递给控制器功能ng-click =“update(user)”?
码
<div ng-controller="ExampleController">
<form novalidate class="simple-form">
Name: <input type="text" ng-model="user.name" /><br />
E-mail: <input type="email" ng-model="user.email" /><br />
Gender: <input type="radio" ng-model="user.gender" value="male" />male
<input type="radio" ng-model="user.gender" value="female" />female<br />
<input type="button" ng-click="reset()" value="Reset" />
<input type="submit" ng-click="update(user)" value="Save" />
</form>
<pre>user = {{user | json}}</pre>
<pre>master = {{master | json}}</pre>
</div>
<script>
angular.module('formExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.master = {};
$scope.update = function(user) {
$scope.master = angular.copy(user);
};
$scope.reset = function() {
$scope.user = angular.copy($scope.master);
};
$scope.reset();
}]);
</script>
最佳答案 HTML中的ng-model =“user.gender”代码引用控制器中的$scope.user.gender.
因为$scope.user已经定义,angular会自动设置该对象的gender属性. user.email和user.name属性也是如此.
当您调用ng-click =“update(user)”时,update(user)与update($scope.user)相同.
This section of the angular tutorial更好地解释了$scope变量如何工作以及如何在模板中访问它,我建议阅读它,但这里是一个快速的exerpt:
The concept of a scope in Angular is crucial. A scope can be seen as the glue which allows the template, model and controller to work together. Angular uses scopes, along with the information contained in the template, data model, and controller, to keep models and views separate, but in sync. Any changes made to the model are reflected in the view; any changes that occur in the view are reflected in the model.