开发者问题收集

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

2016-03-27
628

刚刚得到一个代码,看到代码正在运行,但是在 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>
1个回答

HTML 中的 ng-model="user.gender" 代码引用控制器中的 $scope.user.gender

由于 $scope.user 已定义,因此 angular 会自动在该对象上设置 gender 属性。 user.emailuser.name 属性也是如此。

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

Angular 教程的这一部分 更好地解释了 $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.

Chris Foster
2016-03-27