默认值在我父控制器:AngularJS设置指令
//soemtimes view invoice has taxtotal defined
$scope.viewinvoice = {taxtotal:4}
//sometimes viewinvoice does not have taxtotal defined
$scope.viewinvoice = {}
//sometimes it is defined but equal to 0
$scope.viewinvoice = {taxtotal:0}
在我父视图:
<div class="span6">
<invoice invoice='viewinvoice'></invoice>
</div>
我的指令:
.directive('invoice', [ function() {
return {
restrict: 'E',
scope: {
invoice:'='
},
replace: true,
template: '<div>
<input type="checkbox" ng-model="taxflag">
<div> {{ calculate_grand_total() }} </div>
</div>',
link: function($scope, element, attrs) {
}
};
}]);
在我的指导我想设置$ scope.taxflag基于以下属性的true:$ scope.invoice.taxtotal,问题是如果$ scope.invoice.taxtotal未定义我想设置t他$ scope.taxflag为false,如果$ scope.invoice.taxtotal大于0并且被定义,我希望$ scope.taxflag设置为true。
即
if($scope.invoice.hasOwnProperty('taxtotal')){
if($scope.invoice.taxtotal > 0) {
$scope.taxflag = true;
} else {
$scope.taxflag = false;
}
} else {
$scope.invoice.taxtotal = 0;
$scope.taxflag = false;
}
我想这(上面的代码),要像“初始化”代码,所以每当我的“viewinvoice”父变化$ scope.taxflag和$ scope.invoice.taxtotal将两者最初建立正确
我也想触发的改变,只要选中该复选框:
即
$scope.$watch('taxflag',function(newValue){
if(newValue) {
$scope.invoice.taxtotal = 5
} else {
$scope.invoice.taxtotal = 0;
}
});
我也是用这个$ scope.invoice.taxtotal在别处的函数{{calculate_grand_total()}} (在我的指令查看)
即。
$scope.calculate_grand_total = function() {
return $scope.invoice.taxtotal + 5;
}
但这是无法呈现,因为$ scope.invoice.taxtotal没有定义(至少在初期)!
这是否有意义?我已经尝试了很多不同的组合,但我似乎无法按照我的需要进行工作。
感谢这个让我什么,我想做的事!还有一件事应该是可以在$ scope.taxflag上设置一个观察器,然后我可以更新我的$ scope.invoice.taxtotal?或者我会像当前观察者一样在$ scope.invoice.taxtotal –
上看起来像一个循环循环。如果您查看代码,它实际上会观看税标。只要两只手表都是一致的,那么就不应该有循环。如果手表产生的值与上次运行的时间不同,手表只会触发。例如,当您设置taxflag = true时,它会触发设置taxtotal = 5的手表。这会触发taxtotal手表,然后将taxflag再次设置为true,但这不会再次触发taxfglag手表,因为该值没有更改(它仍然是真正的,这是最后一次它运行相同) – dtabuenc
哎呀,是的,我现在看到它没有注意到这名运动员在税标上有$ watch。非常感谢 !! –