简体   繁体   中英

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).

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..

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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