gpt4 book ai didi

angularjs - 我们如何在 Angular 的 ng 模型中使用未定义的属性

转载 作者:行者123 更新时间:2023-12-01 03:33:52 25 4
gpt4 key购买 nike

刚得到一个代码,看到代码在工作,但在 ng-model作者使用 user.name 或 user.email 等,但这些属性从未在 Controller 中声明......那么它是如何工作的?

我们如何以这种方式将用户信息传递给 Controller ​​功能 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>

最佳答案

ng-model="user.gender" HTML 中的代码是指 $scope.user.gender在 Controller 中。

因为$scope.user已定义, Angular 自动设置 gender该对象的属性。 user.email 也是如此。和 user.name特性。

当您调用 ng-click="update(user)" , update(user)update($scope.user) 相同.

This section of the angular tutorial更好地解释了 $scope变量的工作原理以及如何在模板中访问它,我建议您通读它,但这里有一个简短的摘录:

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.

关于angularjs - 我们如何在 Angular 的 ng 模型中使用未定义的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36251956/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com