AngularJS新手问题。我想写个密谋指令。假设我有这个:
app.controller("dirCtrl", function($scope) {
$scope.datapoints = [
{ x: 1.169, y: 1.810, label: "Point-0" },
{ x: 1.585, y: 0.508, label: "Point-1" },
{ x: 7.604, y: 2.735, label: "Point-2" },
...
];
});那么我希望我的指令是这样的:
<my-plot xLabel="Some Numbers" xUnits="grams"
yLabel="Some Values" yUnits="mm"
data="datapoints" />我的问题是“数据点”没有绑定到$scope.datapoints --我也尝试过以data="{{datapoints}}"的形式编写属性,但也没有成功。
我的指令定义,在它自己的模块中:
angular.module("plotDirectives", [])
.directive("myPlot", function() {
return {
restrict: "E",
scope: true, //'cos I want access to the controller's scope right?
link: function(scope, iElement, iAttrs) {
/* would draw fancy chart if I only could access
the datapoints in the 'data' attribute */
};
});我缺少了什么,或者对于我的指令来说,获得控制器范围数据点的更好的方法是什么?谢谢。
发布于 2015-01-29 13:48:14
您可以在指令中使用隔离作用域。
下面是来自AngularJS正式文件的一个例子。
angular.module('docsIsolateScopeDirective', [])
.controller('Controller', ['$scope', function($scope) {
$scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' };
$scope.igor = { name: 'Igor', address: '123 Somewhere' };
}])
.directive('myCustomer', function() {
return {
restrict: 'E',
scope: {
customerInfo: '=info'
},
templateUrl: 'my-customer-iso.html'
};
});
<div ng-controller="Controller">
<my-customer info="naomi"></my-customer>
<hr>
<my-customer info="igor"></my-customer>
</div>如果在指令中使用scope: true (这在大多数情况下是不好的实践,因为它使指令与控制器紧密耦合),则不需要为指令设置DOM属性,只需使用scope.yourVariableName通过继承访问控制器中的变量。
https://stackoverflow.com/questions/28215993
复制相似问题