如何将过滤器传递给Angular中的指令?

时间:2016-04-27 18:36:35

标签: angularjs

this question类似,我有一个指令,我想在几种不同的情况下使用。我传递了一个可以使用的值,但我也希望传入一个过滤器来应用它。这样做的正确语法是什么?

string testid = xliff.Descendants()
                     .Elements(xmlns + "trans-unit")
                     .Elements(xmlns + "seg-source")
                     .Elements(xmlns + "mrk")
                    .Where(e => e.Attribute("mtype").Value == "seg" && e.Attribute("mid").Value == SegId)
                    .Select(n => n.Parent.Parent.PreviousNode as XElement)
                    .Where(c => c.Elements(xmlns + "target") == null && c.Elements(xmlns + "source").Elements(xmlns + "x").Last().Value != null)
                    .FirstOrDefault().Attribute("id").Value;

模板:

function Drink(full,alcoholic){
  this.alcoholic  = alcoholic;
  this.full   = full;
}

function Person(name,age){
  this.name = name;
  this.age = age;
  this.drinking= function drinking(drink) {
    if (age>=18) {
        drink.full=false;    
    } else {
      console.log("no puede tomar")
      drink.full=true;
    };
  }
}

John = new Person("John",24);
Sam = new Person("Sam",2);
x = new Drink(true,true);

console.log(x)
console.log(John.drinking(x))
console.log(Sam.drinking(x))

使用:

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>

2 个答案:

答案 0 :(得分: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 :(得分:0)

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