我正在尝试创建一个角度指令,可以在其中通过单个选项对象或某些属性来设置选项。这是这种代码的示例:
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] 删除。
我来说两句