简体   繁体   English

Angular自定义指令在过滤器中使用范围变量

[英]Angular custom directive use scope variable in filter

I am having a little trouble with my angular custom directive. 我的角度自定义指令遇到了一些麻烦。 I want to access the "type"-variable in my filter, which is filterung objects (on the first level, so it should be possible without a custom filter). 我想访问我的过滤器中的“类型”变量,它是filterung对象(在第一层,因此无需自定义过滤器就应该可以)。

This is the (very basic so far) structure: 这是(到目前为止非常基本的)结构:

angular.module('....').directive('ngTest', function () {
return {
  restrict: 'AE',
  replace: 'true',
  scope: {
    list: '=',
    type: '@'
  },
  template: '<div><ul><li ng-repeat="information in list | filter:{ttype:type}">....</li></ul></div>'
  }
});

Is there a way to access the variable in the template-string? 有没有办法访问模板字符串中的变量? Neither escaping nor using a template html file worked for me.. 转义或使用模板html文件都不适合我。

Thanks, Chris 谢谢克里斯

Construct your filter from the scope variables using the link function. 使用链接函数从范围变量构造过滤器。

It's slightly less awkward, and it will give you more flexibility to alter the filter in the future. 它稍显尴尬,并且在将来更改过滤器时将为您提供更大的灵活性。

angular.module('....').directive('ngTest', function () {
  return {
    restrict: 'AE',
    replace: 'true',
    scope: {
      list: '=',
      type: '@'
    },
    template: '<div><ul><li ng-repeat="information in list | filter:filterOb">....</li></ul></div>',
    link: function(scope, element, attrs) {
      scope.filterOb = { ttype: scope.type }
    }
  }
});

Here is a working plunk where instead you pass the whole filter object to the directive, instead of just a string - that way you can filter on anything you want without altering the directive 这是一个工作的小插曲 ,您可以将整个过滤器对象传递给指令,而不仅仅是一个字符串-这样,您可以在不更改指令的情况下对任何想要的内容进行过滤

After renaming the variables and rewriting the directive it suddenly works: 重命名变量并重写指令后,它突然起作用:

    <li ng-repeat="information in list | filter:{ttype:type}">{{information.value}}</li>

Sometimes its just.. awkward. 有时它只是..尴尬。 Nevertheless: Thanks! 不过:谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM