ng -s中的angularjs双向绑定

时间:2017-10-31 16:28:28

标签: angularjs angularjs-ng-repeat angular-ngmodel

我有一个Angular控制器变量,用于定义我想在模板中渲染的一堆字段的外观。我的底层模型的初始值正确地出现在input元素中,但是当我更改该元素的内容时它不会改变。

以下是一些代码:

app.js

(function() {
  var app = angular.module("my_app", []);
    app.controller("MyController", function() {
      var my_controller = this;
      my_controller.model = {
        "first_name": "fred",
        "last_name": "jones"
      }
      my_controller.fields = [
         {
          "name": "first_name",
          "label": "First Name",
          "is_required": true,
          "model": my_controller.model.first_name
         },
        {
          "name": "last_name",
          "label": "Last Name",
          "is_required": true,
          "model": my_controller.model.last_name
         }
       ]
})();

template.html:

<div ng-app="my_app">
  <div ng-controller="MyController as my_controller">
    <div ng-repeat="field in my_controller.fields">
      {% verbatim ng %}
        <label for="id_{{ field.name }}" ng-class="field.is_required ? 'required' : 'optional'">{{ field.label }}:&nbsp;</label>
        <input type="{{ field.type }}" class="form-control" name="{{ field.name }}" id="id_{{ field.name }}" ng-model="field.model">
      {% endverbatim ng %}
     </div>
  </div>
</div>

(不要担心“{%verbatim ng%}”的东西 - 就在那里b / c我正在使用Django。)

这正确显示两个输入字段,初始值分别为“fred”和“jones”。但是当我更改这些字段中的值时,my_controller.model对象没有相应的更改。

任何提示?

感谢。

1 个答案:

答案 0 :(得分:1)

执行此操作"model": user_controller.model.first_name只会为model字段指定值,但不会创建对my_controller.model.field_name的引用。

您只需使用bracket notation修改my_controller.model字段:

&#13;
&#13;
angular.module('app', [])
.controller('testController',
  function testController($scope) {
  
      var my_controller = this;
      
      my_controller.model = {
        first_name: "fred",
        last_name: "jones"
      };
      
      my_controller.fields = [
         {
          "name": "first_name",
          "label": "First Name",
          "is_required": true
         },
        {
          "name": "last_name",
          "label": "Last Name",
          "is_required": true
         }
       ];
       
});
&#13;
<body ng-app="app">
<div class="table-responsive" ng-controller="testController as my_controller">
      <div ng-repeat="field in my_controller.fields">
  
        <label for="id_{{ field.name }}" ng-class="field.is_required ? 'required' : 'optional'">{{ field.label }}:&nbsp;</label>
        <input type="{{ field.type }}" class="form-control" name="{{ field.name }}" id="id_{{ field.name }}" ng-model="my_controller.model[field.name]">

     </div>
     -----------------------------------
     <br/>
     <code>{{my_controller.model}}</code>
</div>
</body>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
&#13;
&#13;
&#13;