在 angularJs 过滤器方法中获取对象上下文?

Get object context in angularJs filter method?

我完全被难住了。我不明白为什么我要在我的 plunker(第 51 行)中获取对象的父范围。

据我所知,看起来 Angular 必须在过滤器上调用 .call() 或 .apply(),将其上下文设置为当前 $scope 或其他内容。但这看起来很奇怪,为什么不直接调用方法并单独保留上下文呢?

angular.module('MyApp', [])
.controller('MyCtl', function(
  $scope,
  WidgetsService
){
  WidgetsService.getWidgets().then(function(widgets){
    $scope.entireWidgetsList = widgets;
  });

})
.directive('widgetsFilteredList', function(
  WidgetsService
){
  return{
    restrict: 'E',
    scope: {
      filter: '='
    },
    templateUrl: 'widgets-filtered-list.directive.html',
    controller: function($scope){
      $scope.typeAheadModel = null;
      $scope.widgetsResults = null;
      $scope.$watch(function(){
        return ($scope.typeAheadModel) ? $scope.typeAheadModel : null;
      }, function(newV, oldV){
        if(newV && newV != oldV){
          var reqPromise = WidgetsService.getWidgets();

          reqPromise.then(function(widgets){
            $scope.widgetsResults = widgets;
          }, angular.noop);
        }
      });
    }
  };
})
.factory('WidgetFactory', function(){
  function Widget(data){
    var defaultStructure = {
      id: null,
      color: null,
      cogs: []
    };

    _.merge(this, defaultStructure, data);
  }

  Widget.prototype.widgetFilter = function(){
    var self = this;
    return function(widget){
      console.log(self); //How the heck do I get this to give me the proper context??
      //compare 'widget' this the widget in context for return value.  Like:
      // return !!!(widget.id === self.id);  //Would remove the context widget from the result set;
      return true;
    }
  };

  var create = function(data){
    return new Widget(data);
  };

  return {
    create: create
  };
})
.service('WidgetsService', function(
  WidgetFactory,
  $q,
  $timeout
){
  return {
    getWidgets: function(){
      var def = $q.defer();

      $timeout(function(){
          var widgetResults = [
            WidgetFactory.create({
              id:1,
              color: 'red',
              cogs: []
            }),
            WidgetFactory.create({
              id:2,
              color: 'blue',
              cogs: [1, 2]
            }),
            WidgetFactory.create({
              id:3,
              color: 'green',
              cogs: []
            }),
            WidgetFactory.create({
              id:4,
              color: 'yellow',
              cogs: []
            })
          ];

          def.resolve(widgetResults);
      }, 500);

      return def.promise;
    }  
  };
});

您将 widgetFilter 作为闭包传递给 $scope,这就是为什么您看到 console.log(self) 输出是 $scope 对象的原因。而是像这样将 widgetfilter 函数放在工厂中:

.factory('WidgetFactory', function(){
  function Widget(data){
    var defaultStructure = {
      id: null,
      color: null,
      cogs: []
    };

    var self=this
    this.widgetFilter=function(){
      console.log(self)
    }

    _.merge(this, defaultStructure, data);
  }