我有一个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 }}: </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
对象没有相应的更改。
任何提示?
感谢。
答案 0 :(得分:1)
执行此操作"model": user_controller.model.first_name
只会为model
字段指定值,但不会创建对my_controller.model.field_name
的引用。
您只需使用bracket notation修改my_controller.model
字段:
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 }}: </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;