2014-03-12 36 views
0

我想在服务中创建一个新元素,编译它并将其附加到主体(消息框)。 我的问题是如何以及如何在服务中创建新元素并将其附加到DOM,以及是否有更好的方法来实现它(它应该在服务中)。Angular创建指令与服务

我的问题是,我不能绑定属性,该指令的范围:

我得到了下面的代码:

方法在我的服务

_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);    
}; 

使用创造新元素服务

var buttons = ['Eins', 'Zwei']; 
mbs.createMessageBox('Nachricht', buttons); 

指令

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 
     }; 
}); 

当我这样做的,我得到这个错误,属性不绑定

错误:[$解析:语法]语法错误:令牌“”是的5列一个意外标记从[,Zwei]开始的表达式[Eins,Zwei]。

+0

你为什么要在服务?是因为你希望它可以通过你的所有控制器访问吗? 我看到你正在创建一个指令元素,然后将html元素附加到它像文本和按钮你想实现什么请详述 –

+0

是的我想要一个服务,因为可访问性。控制器应该能够注入服务,然后使用createMessageBox方法在某些使用情况下创建一个消息框。我没那么深,但我希望这种方法可以 –

回答

0

我发现我的问题的解决方案的指令作出反应,

msgBox.setAttribute('text', text); 
msgBox.setAttribute('buttons', buttons); 

这只是设置为一个常量字符串的属性,解决方案是创建属性的范围我创建的元素加上我不得不把一个字符串作为属性,而不是一个变量

此代码工作:

_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);    
};