Javascript 属性内的角度指令范围继承
AngularJS新手问题。我想写一个绘图指令。假设我有这个:Javascript 属性内的角度指令范围继承,javascript,angularjs,Javascript,Angularjs,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"
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" />
我遗漏了什么,或者我的指令获取控制器范围数据点的更好方法是什么?谢谢。您可以在指令中使用隔离作用域 这里有一个例子
angular.module('docsIsolateScopeDirective',[])
.controller('controller',['$scope',function($scope){
$scope.naomi={名称:'naomi',地址:'1600圆形剧场'};
$scope.igor={名称:'igor',地址:'123某处'};
}])
.directive('myCustomer',function(){
返回{
限制:'E',
范围:{
customerInfo:'=信息'
},
templateUrl:“我的客户iso.html”
};
});
如果在指令中使用
scope:true
(这在大多数情况下是一种不好的做法,因为它使指令与控制器紧密耦合),则不需要为指令在DOM上设置属性,只需使用scope.yourVariableName
通过继承访问控制器中的变量。我知道这个示例,但没有尝试从link函数访问变量。就这么做了,而且成功了。它也适用于我的积分列表。谢谢。作为将来的参考,我认为如果您在控制器上使用别名语法,就不会出现问题。通过避免直接注入$scope,它消除了与之相关的问题。我不认为别名语法在这个例子中会有帮助,因为这更像是我的误解。但是这个链接很有用,包含我不知道的信息,以后会很方便。非常感谢。
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 */
};
});
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>