単一のオプションオブジェクトまたはいくつかの属性を介してオプションを設定できる角度ディレクティブを作成しようとしています。コードの種類の例を次に示します。
app.directive('testElement', [function () {
return {
restrict: "E",
scope: {
options: "="
},
template: "<p><span>Name: </span>{{ options.name }}</p>",
link: function (scope, element, attrs) {
scope.options = scope.options || {};
if (attrs.name)
scope.options.name = attrs.name;
}
};
}]);
これは、options属性を介して名前を渡すと、名前の値が表示されるという点で正常に機能します。しかし、name属性を介して名前を渡すと、リンク関数がオプションを変更しても、値はレンダリングされません。
http://plnkr.co/edit/IMVZRdAW2a5HvSq2WtgT?p=preview
オプションの双方向データバインディングがどのように機能するかについて、基本的な何かが欠けているように感じます。
双方向のデータバインディングを渡さないと、angularは怒ります。
https://github.com/angular/angular.js/issues/1435
オプションのバインディングを使用する(=?):
app.directive('testElement', [function () {
return {
restrict: "E",
scope: {
options: "=?"
},
template: "<p><span>Name: </span>{{ options.name }}{{ test }}</p>",
link: function (scope, element, attrs) {
scope.options = scope.options || {};
if (attrs.name)
scope.options.name = attrs.name;
}
};
}]);
または、古いバージョンのangularを使用している場合は、attrsで$ evalを使用します。オプション:
app.directive('testElement', [function () {
return {
restrict: "E",
//Still can create isolate scope to not clobber parent scope variables.
scope: {},
template: "<p><span>Name: </span>{{ options.name }}{{ test }}</p>",
link: function (scope, element, attrs) {
scope.options = scope.$eval(attrs.options) || {};
if (attrs.name)
scope.options.name = attrs.name;
}
};
}]);
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加