我处于一种奇怪的情况,我需要为选定的 Angular 元素创建一个动态 View 模型。
考虑我的 html View 中有三个不同的指令,名为 <paragragh>
它们都连接到一个 Controller ,ParagraphController
。由于我需要在它们之间共享设置,因此我定义了一个服务来保存名为 ParagraphConfig
的共享变量。它连接到名为 ParagraphConfigConroller
的 Controller .
paragraph.config.js
(function() {
'use strict'
angular
.module('Application')
.directive('ParagraphConfig', ParagraphConfigService);
function ParagraphConfigService() {
var paragraph = {
text: 'blah blah',
style: {
fontWeight: 'normal',
border: 0
}
}
return {
get: get
}
function get() {
return paragraph;
}
}
})();
config.controller.js
-> controllerAs: ParagraphConfigViewModel
(function() {
'use strict'
angular
.module('Application')
.directive('ParagraphConfigController', ParagraphConfigController);
function ParagraphConfigController( ParagraphConfig.get ) {
var self = this;
self.paragraph = ParagraphConfig.get();
}
})();
paragraph.directive.js
(function() {
'use strict'
angular
.module('Application')
.directive('paragraph', ParagraphDirective);
function ParagraphDirective() {
return {
restrict: 'E',
templateUrl: '/path/to/templates/paragraph.html',
scope: true,
replace: true,
require: '^component',
controller: 'ParagraphController',
controllerAs: 'ParagraphViewModel'
}
}
})();
paragraph.controller.js
-> controllerAs: ParagraphViewModel
(function() {
'use strict'
angular
.module('Application')
.directive('ParagraphController', ParagraphController);
function ParagraphController( ParagraphConfig.get ) {
var self = this;
self.paragraph = ParagraphConfig.get();
}
})();
实际上我正在使用ParagraphConfig
共享/更改每个段落的设置。以下是我将设置绑定(bind)到每个 p
的方法标签。
我有一个paragraph.html
和一个 config.html
如下。
paragraph.html
<p ng-style="ParaghViewModel.paragraph.style">
{{ParagraphViewModel.paragraph.text}}
</p>
config.html
<input type="radio" name="font weight"
ng-model="ParagraphViewModel.fontWeight" value="bold"> Bold
<input type="radio" name="font weight"
ng-model="ParagraphViewModel.fontWeight" value="normal"> Normal
现在的问题是,当我选择一个段落(我有一个设置 Pane ,将通过单击每个段落激活它)并尝试更改其设置时,它会影响其他段落。
是否有任何解决方案可以通过单击每个段落来创建独特的 View 模型?!
最佳答案
如果你只想用服务初始化段落,你可以使用工厂函数;
function ParagraphConfigService() {
return {
get: get
}
function get() {
return {
text: 'blah blah',
style: {
fontWeight: 'normal',
border: 0
}
};
}
}
如果你想与服务同步数据,你应该使用带有多个配置对象的工厂函数
function ParagraphConfigService() {
var paragraphs = [create(), create(), create()]; // for example as array;
return {
get: get
}
function get(index){
return paragraphs[index];
}
function create() {
return {
text: 'blah blah',
style: {
fontWeight: 'normal',
border: 0
}
};
}
}
关于javascript - 为相似的 Angular 对象动态创建 View 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39423778/