如何将滤镜转换为angularjs中的指令

时间:2018-02-05 11:34:06

标签: javascript angularjs

This is my old question,我想从输入字段中过滤掉负数:

<input type = "text" ng-model="number"></input>

在我的旧问题中,Paritosh给了我good answer,但我需要将该代码从filter转换为指令。如何将其转换为指令?

app.filter('nonNegative', function(){
  return function(val){
     if(val >= 0) return val; else '';
  }
})

1 个答案:

答案 0 :(得分:0)

您必须在指令

中包含ngmodel
app.directive('myDirective', function(){
return{ 
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, element, attrs,ngModel){
       // Your filter operation
       if(scope.number < 0)
         scope.number = 0;
    }
}
});

第一次加载元素时这将起作用