2016-06-16 12 views
0

角度指令のデフォルトパラメータをどのように設定できますか?ここで角度指令のデフォルトパラメータ

は、HTMLでdirecitveです:

<product product="product" isfavorites="true"></product> 

私はisfavoritesがデフォルト値falseを持って欲しいです。したがって、true返信falseに設定されていない場合。 どうすればいいですか?

+0

ディレクティブのコードはなんですか?ディレクティブコントローラまたはリンク関数の内部で –

+0

がある場合は、isfavouritesが定義されていないか空であるかどうかを確認し、falseに設定します。 – gaurav5430

答えて

1

Javascriptでは、未定義のプロパティ(isfavoriteなど)は偽のブール値として認識されます。ディレクティブの中には、自動的にfalseになるisfavoriteプロパティを宣言する必要があります。 MDNドキュメントに記述されたよう

$scope.isfavorite; //this is undefined, therefore evaluated as false 

値が省略されるか0であり、-O、ヌル、偽、NaNで、未定義、または空の文字列( "")である場合、オブジェクトが持っています初期値はfalseです。

0

@ gaurav5430はリンク機能で確認できます。このためにはattrsparamと値を取得します。その値が空の場合はfalse、そうでない場合はtrueです。

// Code goes here 
 
var app = angular 
 
    .module('MyApp', [ 
 
    ]) 
 
.controller('Main', ['$scope', function ($scope) { 
 
    var self = this; 
 
    
 
    self.products = [{"productName":"a","id":12},{"productName":"b","id":"34"}]; 
 
    self.test = function(name){ 
 
     alert(name); 
 
     } 
 
    
 
}]) 
 
.directive('product', ['$compile', function($compile) { 
 
    return { 
 
     restrict: 'E', 
 
     transclude: true, 
 
     scope: { 
 
      products: '=', 
 
      ngModel : '=', 
 
      isfavorites:'@' 
 
     }, 
 
     controller:"Main as myCtrl", 
 
     link: function(scope, element, attrs) { 
 
      
 
      console.log(attrs.isfavorites); 
 
      if(attrs.isfavorites == '') 
 
      alert("false") 
 
      else 
 
       alert("true"); 
 
      var template = 
 
       '<ul>' + 
 
        '<li data-ng-repeat="product in products |filter:{id:ngModel}" ng-click="myCtrl.test(product.productName)" >' + 
 
         '{{product.productName}}' + 
 
        '</li>' + 
 
       '</ul>'; 
 

 
      // Render the template. 
 
      element.html('').append($compile(template)(scope)); 
 
     } 
 
    } 
 
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div class="main-content" ng-app="MyApp" ng-controller="Main as myCtrl"> 
 
     <div> 
 
     <input type="text" ng-model="myCtrl.pID" /> 
 
      <product products="myCtrl.products " ng-model="myCtrl.pID" isfavorites></product> 
 
    </div> 
 
</div>

0

あなたはこの bindToController: { isfavorite: '=?' }, はなく、その値を渡すようなあなたのディレクティブでisfavoriteを定義した場合、デフォルトではfalseとして扱いこれは未定義であり、あなたがデフォルトとしてtrueを与えたい場合このようなことをすることができます controller: function() { this.isfavorite = true; // your code }

0

指示文のリンク方法の始めに変数を取得し、||のようなパターン

directive('product', product); 

product.$inject = ['$scope']; 

function product($scope){ 
    return { 
    restrict: 'E', 
    link: link 
    }; 

    function link(scope, elmt, attrs){ 
    var isfavorities = scope.$eval(attrs.isfavorities) || false; 

    // || false is written only for verbosity and code clearness because undefined variables, if evaluated, are false by nature. 
    // anyway this method is useful when you need default input values quickly 
    } 
}