如果您需要更多信息或希望我澄清任何事情,请告诉我。我尝试了很多不同的方法来解决这个问题,但还没有找到解决方案。
我对 angularJS 比较陌生,我正在尝试构建一个具有多层数据的应用程序。我在控制器 PageController 的主体范围内存储了一些基本的用户信息。然后,我有一个使用 $routeParams (带有控制器 SettingsController)加载的设置表单,其中包含几个用于模板目的的自定义指令。由于指令是嵌套的,因此我使用嵌入将第二个指令加载到第一个指令内。这一切似乎都运作良好。
我的问题是我正在尝试引用该字段user.firstname
从最里面的指令中,并希望使用双向数据绑定来允许对文本框进行更改,从而导致 PageController 范围内的值也发生更改。我知道很多此类问题是由于在 ng-model 中使用原语引起的,但我尝试将所有内容都放在一个额外的对象中,这样我触发原型继承就无济于事了。我在这里做错了什么?
这是一个JSFiddle http://jsfiddle.net/CxNc2/我的代码,尽可能地精简以隔离问题。在此示例中,如果我在直接位于 PageController 作用域上的外部文本框中键入内容,它将修改内部文本框,直到该文本框被修改为止,此时连接将被中断。这似乎就像其他问题中描述的使用原语的问题一样,但我无法弄清楚问题出在哪里。
HTML:
<body class="event-listing" ng-app="app" ng-controller="PageController">
<div class="listing-event-wrap">
<input type="text" ng-model="user.firstname" />
<div ng-controller="SettingsController">
<section block title="{{data.updateInfo.title}}" description="{{data.updateInfo.description}}">
<div formrow label="{{data.updateInfo.labels.firstname}}" type="textInput" value="user.firstname"></div>
</section>
</div>
</div>
</body>
角度指令:
app.directive('formrow', function() {
return {
scope: {
label: "@label",
type: "@type",
value: "=value"
},
replace: true,
template: '<div class="form-row">' +
'<div class="form-label" data-ng-show="label">{{label}}</div>' +
'<div class="form-entry" ng-switch on="type">' +
'<input type="text" ng-model="value" data-ng-switch-when="textInput" />' +
'</div>' +
'</div>'
}
});
app.directive('block', function() {
return {
scope: {
title: "@title",
description: "@description"
},
transclude: true,
replace: true,
template: '<div class="page-block">' +
'<h2 data-ng-show="title">{{title}}</h2>' +
'<p class="form-description" data-ng-show="description">{{description}}</p>' +
'<div class="block-inside" data-ng-transclude></div>' +
'</div>'
}
});
角度控制器:
app.controller("PageController", function($scope) {
$scope.user = {
firstname: "John"
};
});
app.controller("SettingsController", function($scope) {
$scope.data = {
updateInfo: {
title: "Update Your Information",
description: "A description here",
labels: {
firstname: "First Name"
}
}
}
});