角JS指令,改变一个2路数据链接功能结合 [英] Angular JS directive, change a 2 way data binding in the link function
问题描述
我试图创造一个角指令,我可以通过一个单一的选择对象,或者通过某些属性设置的选项。这里是那种code的一个例子:
I'm trying to create an angular directive where I can set the options either via a single options object, or via some attributes. Here is an example of the kind of code:
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;
}
};
}]);
这工作得很好,因为如果我通过在一个名字通过选项属性名值显示。但是,如果我通过name属性传递一个名字,即使连接功能不修改选项,该值不渲染。
This works fine, in that the name value is displayed if I pass in a name via the options attribute. But if I pass a name via the name attribute, even though the link function does modify options, the value is not rendered.
http://plnkr.co/edit/IMVZRdAW2a5HvSq2WtgT?p=$p$ PVIEW
我觉得我失去了一些东西在数据绑定选项2路如何工作的基础。
I feel like I'm missing something fundamental in how the 2 way data binding of options works.
推荐答案
如果您没有通过双向数据绑定,角生气:
If you don't pass the two way data binding, angular gets angry:
<一个href=\"https://github.com/angular/angular.js/issues/1435\">https://github.com/angular/angular.js/issues/1435
使用可选的绑定(=):
Use optional binding (=?):
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;
}
};
}]);
或者,如果你使用的是棱角分明,使用$的eval对ATTRS旧版本。选项:
Or if you are using an older version of angular, use $eval on attrs. options:
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;
}
};
}]);
这篇关于角JS指令,改变一个2路数据链接功能结合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!