我试着搜索这个,但我不太清楚如何表达这个想法。让我试着解释一下。我仍在尝试掌握指令的整个范围......
下面的代码是同一指令的一些变体(代码不是很多,只是看起来那样)
说..在我的 Controller 中我有这个
$scope.foo = {name: "John", color: "Green"};
我的指令看起来像这样
app.directive("miniDirective", function () {
return {
restrict: "A",
scope: {
type: "=type",
value: "@value"
},
template:'<div>{{content}}</div>' +
'<input type="text" ng-model="content">',
link: function (scope, iElm, iAttrs) {
switch (scope.value) {
case "name":
scope.content = scope.type.name; break;
case "color":
scope.content = scope.type.color; break;
}
console.log(scope.content);
}
}
})
我想像这样使用我的指令
<div mini-directive
type="foo"
value="name">
</div>
<br/>
<div mini-directive
type="foo"
value="color">
</div>
PROBLEM 1: If I use the above directive then scope.content does not bind back to scope foo (type attribute) value.. I kind of understand why this is,, BUT I have NO idea how to make that happen...
然后我尝试了不同的做法..这就是我卡住的地方,,,
app.directive("miniDirective", function () {
return {
restrict: "A",
scope: {
type: "=type",
value: "@value"
},
template:'<div>{{type.XXXX}}</div>' +
'<input type="text" ng-model="type.XXXX">',
link: function (scope, iElm, iAttrs) {
// I WOULD LIKE TO CHANGE xxxx based on value attribute
// AND keep the binding working
scope.type.xxxx;
}
}
})
问题
有没有一种方法可以将值属性 value: "@value"
中的值转换为可以动态应用于 scope.type.xxxx 的值;其中 xxxx 是名称还是颜色?是否可以像我在第一个示例中那样不使用“switch”或“if else”或任何检查现有值的条件...
或者,,,在我使用 switch 的情况下,有没有办法根据属性中传递的值将 scope.content 绑定(bind)回 foo.name 或 foo.color?
我正在尝试为此制作一个 jsfiddle...
非常感谢您的帮助。
最佳答案
如果您只需要将模板绑定(bind)到外部范围对象的属性,则无需创建隔离范围。
您可以轻松地根据指令的属性创建正确的表达式,如下所示:
var expression = tAttrs.type + '.' + tAttrs.value // foo.name
然后用那个表达式创建一个模板:
'<input ng-model="' + expression + '">' // <input ng-model="foo.name">
您可以将函数传递给指令的模板选项,然后根据需要构建模板。
这是一个笨蛋:http://plnkr.co/edit/ekvPcyXeEPuebmC2mbHP?p=preview
解决方案:
app.directive("miniDirective", function () {
return {
restrict: "A",
template: function(tElm,tAttrs){
var exp = tAttrs.type + "." + tAttrs.value;
return '<div>{{' + exp + '}}</div>' +
'<input type="text" ng-model="' + exp + '">';
}
}
})
如果你因为其他原因需要创建一个独立的作用域
- 使用我上面提到的表达式创建双向数据绑定(bind)。
- 我使用
$parse
进行优化。 - 我按照您在评论中的要求使用
templateUrl
。
另一个 plunker:http://plnkr.co/edit/zG9dbnlUjjr1KTwbVe2i?p=preview
app.directive("miniDirective", function ($parse) {
return {
restrict: "A",
scope:{},
templateUrl: "mini.html",
compile: function(tElm, tAttrs){
var expFn = $parse(tAttrs.type + '.' + tAttrs.value);
return function(scope,elm,attrs){
scope.$parent.$watch(expFn, function(val){
scope.exp = val;
})
scope.$watch('exp', function(val){
expFn.assign(scope.$parent, val)
})
}
}
}
})
和模板:
<div> {{ exp }}</div>
<input type="text" ng-model="exp">
关于javascript - Angularjs - 动态地将属性值附加到绑定(bind)对象。如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21444111/