【发布时间】:2014-01-02 08:13:33
【问题描述】:
我想在没有自己的模板的情况下在 AngularJS 中创建可重用指令。我还希望该指令具有独立的范围。我的方法的最佳实践是什么? 为什么我的示例没有按预期工作?
我希望我可以分别从指令中编辑 obj1 和 obj2。
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);
}
}
});
【问题讨论】:
-
为什么不能使用模板?
-
@Cherniv,这只是一个例子。实际应用程序的用法是这样的:
<div class="block" ng-repeat="block in layout.blocks" size resizable resizable-width="block.width" resizable-height="block.height" draggable draggable-top="block.top" draggable-left="block.left" in-bounds bounds-width="stripe.width" bounds-height="stripe.height">...</div>如果我为每个指令使用模板,代码会看起来(更)丑陋和不可读。
标签: javascript angularjs angularjs-directive angularjs-scope