Jam*_*unt 2 javascript angularjs
我正在尝试创建一个角度指令,我可以通过单个选项对象或某些属性设置选项.以下是这种代码的示例:
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;
}
};
}]);
Run Code Online (Sandbox Code Playgroud)
这样可以正常工作,因为如果我通过options属性传入名称,则会显示名称值.但是,如果我通过name属性传递名称,即使链接函数确实修改了选项,也不会呈现该值.
http://plnkr.co/edit/IMVZRdAW2a5HvSq2WtgT?p=preview
我觉得我缺少一些关于选项双向数据绑定的基本方法.
如果你没有通过双向数据绑定,角会生气:
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;
}
};
}]);
Run Code Online (Sandbox Code Playgroud)
或者如果您使用较旧版本的角度,请在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;
}
};
}]);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4301 次 |
| 最近记录: |