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.
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);
});
}
}
})
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.
Edit: 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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…