AngularJS设置指令的默认值

时间:2013-12-10 06:26:33

标签: angularjs scope directive watch

在我的父控制器中:

//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:$ scope.invoice.taxtotal,问题是如果$ scope.invoice.taxtotal未定义我想将$ 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;
    }
});

我也在函数{{calculate_grand_total()}}的其他地方使用$ scope.invoice.taxtotal (在我的指示视图中)

$scope.calculate_grand_total = function() {
    return $scope.invoice.taxtotal + 5;
}

但是无法渲染,因为$ scope.invoice.taxtotal未定义(至少在最初阶段)!!

这有意义吗?我已经尝试了很多不同的组合,但我似乎无法让它按照我的意愿运行。

2 个答案:

答案 0 :(得分:0)

我创建了这个试图抓住你的问题的plunkr:

http://plnkr.co/edit/02QAC8m9xyF4pSyxnfOf

基本上,任何依赖于可以改变的值的代码都应该在手表中。这意味着用于设置taxflag的初始化代码属于监视,因此如果情况发生变化,它可以更新税标志。这看起来像:

$scope.$watch('invoice.taxtotal', function(taxTotal) {
      if (!angular.isNumber(taxTotal)) {
        $scope.taxflag = false
        return;
      }
      if (taxTotal > 0) {
        $scope.taxflag = true;
      } else {
        $scope.taxflag = false;
      }
    });

请记住,监视总是在第一次初始化值时执行,因此它们实际上既可用作初始化代码,也可用作更新代码。

就您的calculate_grand_total功能而言,如果您需要定义在税务总额或发票未定义时应返回的内容。只需检查它是否未定义并返回适当的值,例如在我的plunkr中我返回空字符串:

$scope.calculate_grand_total = function() {
      if ($scope.invoice && angular.isNumber($scope.invoice.taxtotal)) {
        return $scope.invoice.taxtotal + 5;
      } else {
        return "";
      }
    }

我不确定我的傻瓜是否与你想要的完全一样,但它应该让你开始朝着正确的方向前进。或作为进一步澄清的起点。

答案 1 :(得分:0)

相关


如果您只想设置首次运行的默认值,可以使用UDPBasicApp 在您的链接中:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Travel extends Model 
{
/**
 * The table associated with the model.
 *
 * @var string
 */
protected $table = 'whatever_you_want';
}
相关问题