私は、アプリケーションの共通コントロール用にいくつかの再利用可能なディレクティブを作成中です。例えば既存のディレクティブをコピーする再利用可能なAngularJsディレクティブの作成方法
私たちはそこからスニップ、それをHTMLの量のテキストボックスの
<div class='amount'>
<input type='text' ng-model='dollars'/>
</div>
を持っている私は私のディレクティブを作成するために開始しました:
次<html/>
<div class="amount ng-pristine ng-valid" ng-model="dollars">
<input type="text">
</div>
をレンダリング
app.directive("amount", function(){
return {
restrict: "E",
template: "<div class='amount'><input type='text'/></div>",
replace: true
}
});
ng-model
はにあります私は望んでいないので、スコープを作成してngModel
に添付する必要があり、物事は再びうれしいです。
app.directive("amount", function(){
return {
restrict: "E",
scope:{
ngModel: "="
},
template: "<div class='amount'><input type='text' ng-model='ngModel'/></div>",
replace: true
}
});
すべてが動作しますが、私はまたngChange
ディレクティブに追加したいと言うが、私は再び私scope
ngChange: "="
を含めるように変更する必要がどういう意味しますか?そう
app.directive("amount", function(){
return {
restrict: "E",
scope:{
ngModel: "=",
ngChange : "="
},
template: "<div class='amount'><input type='text' ng-model='ngModel'/></div>",
replace: true
}
});
質問
のように私は常に私が必要とするかもしれない他のディレクティブの無限の可能な数を含めるようにディレクティブのスコープを変更する必要がありますか?または、<amount/>
要素のディレクティブを<div/>
ではなく、<input/>
などにコピーする方法がありますか。
<amount my-awesome-directive="" ng-disabled="form.$invalid" ng-model="dollarsAndCents" ng-click="aClick()" ng-show="shouldShow()"/>
<div class="amount">
<input my-awesome-directive="" type="text" ng-disabled="form.$invalid" ng-click="aClick()" ng-show="shouldShow()" ng-model="dollarsAndCents"/>
</div>
に変わりはそれらをコピーするプリ/ポストコンパイル時に何かを行うことができますか私はすべてが間違ってこれについてつもり?
更新
私は単純にすべての属性を超えるループと$compile()
サービスを使用して経由で作業何かを得ることができました。それはうまくいくが、これは正しいのだろうか?
app.directive("amount", function ($compile) {
return {
restrict: "E",
template: "<div class='amount'><input type='text' /></div>",
replace: true,
compile: function compile(tElement, tAttrs) {
return function (scope, iElement, iAttrs) {
var attributes = $(iElement).prop("attributes");
var $input = $(iElement).find("input");
$.each(attributes, function() { //loop over all attributes and copy them to the <input/>
if (this.name !== "class") {
$input.attr(this.name, this.value);
}
});
$compile($input)(scope); //compile the input
};
}
};
});
あなたはそれが<input/>
<div ng-app="app">
<amount ng-model="dollars" ng-change="changed = 'I Changed!!!'" ng-click="clicked= 'I Clicked It!'" name="amount"></amount>
<h1>{{dollars}}</h1>
<h2>{{changed}}</h2>
<h3>{{clicked}}</h3>
<input type="button" value="Remove" ng-click="items.splice(items.indexOf(item), 1)"/>
<hr/>
</div>
これは古い投稿ですが、属性をコピーしてコンパイルする以外の方法がありますか? –
別のアプローチここで別のアプローチ:http://stackoverflow.com/a/42319665/913845 –