Angularjs孤立的余地没有自己的模板指令 [英] Angularjs isolated scope for directives without own template
问题描述
我要在自己的模板来创建可重用的AngularJS指令。我也想拥有该指令隔离范围。什么是我的方法的最佳实践?
为什么,因为我希望我的例子不工作?
I want to create reusable directive in AngularJS without own template. I also want to have isolated scope for that directive. What is the best practices for my approach? Why my example doesn't work as I expect?
我的预期,我可以OBJ2单独指令编辑OBJ1和
I expected that I could edit obj1 and obj2 from directives separately.
HTML
<div ng-controller="MyCtrl">
X1: {{ obj1.x }}, Y1: {{ obj1.y }}
X2: {{ obj2.x }}, Y2: {{ obj2.y }}
<hr>
Edit obj1:
<div draggable target="obj1">
<input type="text" ng-model="target.x">
<input type="text" ng-model="target.y">
</div>
Edit obj2:
<div draggable target="obj2">
<input type="text" ng-model="target.x">
<input type="text" ng-model="target.y">
</div>
</div>
JS:
angular.module("App", [])
.controller("MyCtrl", function($scope) {
$scope.obj1 = {
x: 10,
y: 20
};
$scope.obj2 = {
x: 30,
y: 40
};
})
.directive("draggable", function() {
return {
scope: {
target: "="
},
link: function(scope, el, attrs) {
console.log("scope: ", scope);
}
}
});
PLUNKR:
http://plnkr.co/edit/Dw8IiFVSOZGjSTFGRMzZ
推荐答案
您code是现在工作的方式,是每个指令的内容被绑定到父范围,而不是指令的隔离范围,所以每个目标
是同一个变量的引用。
The way your code is working now, is that the contents of each directive is bound to the parent scope, and not the isolated scope of the directive, so each target
is a reference to the same variable.
什么你需要做的就是 transclude
指令的内容。这样做的通常使用的是您要的内容是在指令的父作用域,而不是孤立的范围。但是,您想要的内容是在指令的隔离范围。所以你必须手动调用 transclude
函数和内容绑定到该指令的隔离范围:
What you'll need to do is to transclude
the contents of the directive. The usual use for this is that you want the contents to be in the parent scope of the directive, and not in the isolated scope. However, you want the content to be in the isolated scope of the directive. So you'll have to call the transclude
function manually, and bind the contents to the isolated scope of the directive:
.directive("draggable", function($compile) {
return {
transclude: true,
scope: {
target: "="
},
link: function(scope, element, attrs, ctrl, transclude) {
transclude(scope, function(clone) {
element.append(clone);
});
}
}
})
您可以在这个Plunker 看到这一点。一件事没有做到的是 $观看
目标所以我怀疑它不会变化作出反应在指令目标属性的内容。这可能是最好留给另一个问题。
You can see this in this Plunker. One thing it doesn't do is $watch
the contents of the 'target' so I suspect it won't react to changes in the "target" attribute on the directive. This might be best left to another question.
编辑:使用 transclude
的是不正确的/过于复杂。您可以通过范围
作为第一个参数传递给正确的克隆绑定到正确的范围。
the use of transclude
was incorrect / overcomplicated. You can pass the scope
in as the first parameter to properly bind the clone to the correct scope.
这篇关于Angularjs孤立的余地没有自己的模板指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!