WebアプリでUIにTwitterBootstrapを使用しています。特にそのアラートコンポーネント。Bootstrapのアラートをラップする単純なAngularサービスを作成して、Angularコードの平和からユーザーに通知できるようにしたいと思います。このような:
Informer.inform("message", "ERROR"); // will result in alerting with `alert-error` class
Informer.inform("message", "INFO"); // will result in alerting with `alert-info` class
<body>
私の考えは、テンプレートを:の最後に追加することです。
<div class="alert {{alertClass}} fade in informer" id="informer">
<button type="button" class="close" data-dismiss="alert">×</button>
<div class="valignCenterWrapper">
<div class="valignCenter" id="informerMessage">
{{message}}
</div>
</div>
</div>
このようなもの:
grfx.factory("Informer", function() {
return {
inform : function(message, type) {
// Here be dragons. How can I compile/append the template.
$("#inform").alert();
}
};
});
私が知りたい唯一のこと:これをjQueryではなくangularで書くにはどうすればよいですか?上記のコードは開始に適していますか?インターネットの人々は、 DOM操作にはディレクティブのみを使用する必要があると言っています。しかし、私はそれを理解していません。ディレクティブを適用するための既存のマークアップがありません。いくつかの計算/ユーザーの相互作用の結果として、アラートがページに追加されます。temlateをコンパイルして本体のどこかに追加するには、どのサービス(、、)を使用する必要がありますか$compile
?$parse
$document
編集:コントローラーの外部でangularjsサービスを取得することも可能ですか?通常のJSコードで書けるようにgetServiece("Informer").inform("", "")
?
編集2:わかりました、私が今持っているもの:
grfx.factory("Informer", function($compile, $rootScope) {
return {
inform : function(message, type) {
var scope = $rootScope.$new();
scope.message = message;
scope.type = type;
$(document.body).append($compile("<div class='alert {{type}} fade in informer' id='informer'><button type='button' class='close' data-dismiss='alert'>×</button><div class='valignCenterWrapper'><div class='valignCenter' id='informerMessage'>{{message}}</div></div></div>")(scope));
}
};
});
このコードを使用すると、コントローラーから注入されたサービスを使用できます。しかし、Angularコードの外部でサービスを呼び出そうとすると問題が発生します:
angular.element(document).injector().get("Informer").inform("Message", "alert-error");
これはポップアップを表示し{{message}}
ます。たとえば、テンプレートが正しくコンパイルされません。