2016-04-27 107 views
0

this question類似,我有一個指令,我想在兩種不同的情況下使用。我傳遞了一個可以使用的值,但我也想通過一個過濾器來應用它。這樣做的正確語法是什麼?如何將過濾器傳遞給Angular中的指令?

app.directive('showMe', function() { 
    return { 
    restrict: 'E', 
    scope: { 
     value: '=', 
     filter: '=', 
     placeholder: '=' 
    }, 
    templateUrl: 'show-me.html' 
    }; 
}); 

模板:

<input ng-model="value" ng-show="editMode" placeholder="{{placeholder}}" /> 
<p ng-hide="editMode">{{(value | percent)||placeholder}}</p> 

使用:

<show-me value="item.discount" filter="percent" placeholder="0%" /> 

預期的結果:

<input value="25" placeholder="0%" /> 
or 
<p>25%</p> 

回答

3

你可以在一個基本水平實現這一目標通過使用下面的方法;只需在您的指令控制器中使用過濾器提供程序來解析給定的值。例如:

<my-directive value="1461782417" filter="date"></my-directive> 

在「myDirective」你可以很容易地實現濾波器是這樣的:

angular 
    .module('myApp') 
    .directive('myDirective', { 
    restrict: 'E', 
    template: '<span>{{displayValue}}</span>', 
    scope: { 
     value: '=', 
     filter: '=' 
    }, 
    controller: ['$scope', '$filter', function ($scope, $filter) { 
     // Pass the value 
     $scope.displayValue = $filter($scope.filter)($scope.value); 
    }] 
    }); 
+1

是的,這對我有效。我在函數中封裝了displayValue,儘管它處理更多情況:'return $ scope.value? ($ scope.filter?$ filter($ scope.filter)($ scope.value):$ scope.value):$ scope.placeholder;' –

+0

根據AngularJS文檔,如果您願意,可以進一步擴展。過濾器可以採用以下參數:$ filter('filter')(array,expression,comparator)'(第一個參數,「array」,即$ scope.value) –

0
.filter('percent', function() { 
     return function (text, length, end) { 
      if (text == null || text == '') text = '0'; 
      text = parseInt(text)/100; 
      return text.toFixed(2); 
    }; 
+0

嗯,不行 - 我有一個過濾器來執行轉換。我在問如何將它傳遞給要使用的指令。 –