I am in a strange situation in which I need to create an on the fly view model for selected angular element.
Consider I have three different directives in my html view called <paragragh> and they all are connected to a single controller, ParagraphController. Since I need to share a setting between them, I've defined a service to hold my shared variables named ParagraphConfig which is connected to a controller called ParagraphConfigConroller.
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();
}
})();
Actually I'm using ParagraphConfig to share/change settings of each paragraph. Here is how I bind settings to the each p tag.
I have a paragraph.html and a config.html as follow.
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
Now the problem is, when I select a paragraph ( I have a setting pane which will be activated by clicking on each paragraph ) and try to change its setting, it affects other paragraphs.
Is there any solution to create a unique view model by clicking on each paragraph?!
angularjs, you are giving me ac++example!!!