Angularjs 指令隔离范围是否可以在指令内部用于计算
如果定义了一个指令,是否可以在该指令中使用通过其上定义的属性传递给它的范围,以获得在模板中使用所需的结果?i、 我有这样的指示Angularjs 指令隔离范围是否可以在指令内部用于计算,angularjs,angularjs-directive,Angularjs,Angularjs Directive,如果定义了一个指令,是否可以在该指令中使用通过其上定义的属性传递给它的范围,以获得在模板中使用所需的结果?i、 我有这样的指示 var carAuction = angular.module('carAuction'); carAuction .controller('mainCtrl', function($scope) { var car = { comments: [] }; car.comment
var carAuction = angular.module('carAuction');
carAuction
.controller('mainCtrl', function($scope)
{
var car = {
comments: []
};
car.comments.push({
comment: 'Ok car',
rating: 1
});
car.comments.push({
comment: 'Nice car.',
rating: 2
});
car.comments.push({
comment: 'Awesome car!',
rating: 3
});
$scope.car = car;
})
.directive('carCommentRaiting', function()
{
return
{
restrict: 'E',
templateUrl: 'path/to/template.html',
scope:
{
value: '=value',
maxValue: '=max-value'
}
};
})
.filter('range', function()
{
return function(input, total)
{
total = parseInt(total);
for (var i=1; i<=total; i++)
{
input.push(i);
}
return input;
};
});
但由于某些原因,它并不总是有效。一次有效,另一次计算的
变量为null
所有计算必须在direcitve链接函数或控制器中完成。
以下是指令的示例:
.directive('carCommentRaiting', function() {
return {
restrict: 'E',
template: 'path/to/template.html',
scope: {
value: '=value',
maxValue: '=max-value'
},
link : function(scope, element, attr) {
scope.calculated = scope.maxValue - scope.value;
/// watch value to update calculated on value update:
scope.$watch('value', function(newValue){
scope.calculated = scope.maxValue - newValue;
});
}
};
});
请在controller中发布template.html
或fiddle,但没有解决问题,但link属性是我正在寻找的魔法。此外,无需计算外部$watch
。非常感谢。
<div>
<ul class="list-inline">
<li ng-repeat="n in [] | range:value"><span class="glyphicon glyphicon-star"></span></li>
</ul>
</div>
return {
restrict: 'E',
templateUrl: 'path/to/template.html',
scope:
{
value: '=',
maxValue: '='
},
controller: function($scope)
{
$scope.calculated = $scope.maxValue - $scope.value;
}
};
.directive('carCommentRaiting', function() {
return {
restrict: 'E',
template: 'path/to/template.html',
scope: {
value: '=value',
maxValue: '=max-value'
},
link : function(scope, element, attr) {
scope.calculated = scope.maxValue - scope.value;
/// watch value to update calculated on value update:
scope.$watch('value', function(newValue){
scope.calculated = scope.maxValue - newValue;
});
}
};
});