Reputation: 625
I want to create a new element within a service, compile it and append it to the body (a message box). My question is if and how it's possible to create a new element in a service and append it to the DOM and if there's a better way to do it maybe (it should be in a service tho).
My problem is that I can't bind attributes to the directive's scope:
I got the following code:
Method to create new element in my service
_createMessageBox = function (text, buttons) {
var msgBox = document.createElement('message-box');
msgBox.setAttribute('class', 'messageBox');
msgBox.setAttribute('text', text);
msgBox.setAttribute('buttons', buttons);
$compile(msgBox)(scope);
$('body').append(msgBox);
};
Use of the service
var buttons = ['Eins', 'Zwei'];
mbs.createMessageBox('Nachricht', buttons);
directive
app.directive('messageBox', function () {
link = function (scope, element, attrs) {
scope.buttonClicked = function(id) {
this.$emit('button'+id+'_clicked');
}
}
return {
restrict: 'E',
scope:
{
text: '=',
buttons: '='
},
link: link
};
});
When I do it that way I get this error and the attributes aren't binded
Error: [$parse:syntax] Syntax Error: Token ',' is an unexpected token at column 5 of the expression [Eins,Zwei] starting at [,Zwei].
Upvotes: 0
Views: 132
Reputation: 625
I found the solution for my problem,
msgBox.setAttribute('text', text);
msgBox.setAttribute('buttons', buttons);
this was just setting the attribute as a constant string, the solution was to create the property for the scope I created the element with plus I had to hand a string as attribute, not a variable
This code is working:
_createMessageBox = function (text, buttons) {
scope.text = text;
scope.buttons = buttons;
var msgBox = document.createElement('ext-message-box');
msgBox.setAttribute('class', 'extMessageBox');
msgBox.setAttribute('text', 'text');
msgBox.setAttribute('buttons', 'buttons');
$compile(msgBox)(scope);
$('body').append(msgBox);
};
Upvotes: 0
Reputation: 3493
You have dependency on a directive and service so you should be using a provider not a service for this refer http://docs.angularjs.org/guide/providers
secondly your directive has an isolated scope so even if you perform events at a controller level you wont be able to respond from the directive as per your requirements in the comments section i would advise you to use $modal service in http://angular-ui.github.io/bootstrap/
Upvotes: 1