我是 angularjs 的新手,我不确定这是否是正确的方法 我正在尝试做类似的数学,所以我想把它放在指令中
myApp.directive('getDistance',function(Auth){
var R = 6371;
return {
restrict: 'AE',
template: '{{distance}}',
scope: {
value: '=value',
maxValue: '=max-value'
},
link : function(scope, element, attr) {
$scope.$apply(function(){
$scope.distance = scope.maxValue - scope.value;
});
}
};
});
同一指令将在同一页面中多次使用,我认为每个指令都将使用相同的距离。我该如何解决这个问题或更好的方法?
最佳答案
您的指令存在多个问题。您可以修复它们并同时改进代码。
首先,maxValue: '=max-value'
不是正确的独立作用域属性定义。属性/特性名称必须使用驼峰式命名:maxValue: 'maxValue'
。
修复了这个问题后,您就可以一起删除右侧的名称并使用 =
符号,因为范围名称在相应的属性中是相同的。
最后,在链接函数中,您引用了错误的作用域变量 $scope
。最终指令如下所示:
myApp.directive('getDistance', function(Auth) {
var R = 6371;
return {
restrict: 'AE',
template: '{{distance}}',
scope: {
value: '=',
maxValue: '='
},
link: function(scope, element, attr) {
scope.distance = scope.maxValue - scope.value;
}
};
});
演示:http://plnkr.co/edit/3pbe9Z3e40JT5far4ijK?p=preview
关于javascript - angularjs指令做算术,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26980262/