programing

Angular의 필터에서 범위 변수에 액세스합니다.JS

goodjava 2023. 2. 15. 22:02

Angular의 필터에서 범위 변수에 액세스합니다.JS

지나가고 있습니다date값을 커스텀 필터에 다음과 같이 설정합니다.

angular.module('myapp').
  filter('filterReceiptsForDate', function () {
    return function (input, date) {
      var out = _.filter(input, function (item) {
        return moment(item.value.created).format('YYYY-MM-DD') == date;
      });
      return out;
    }
  });

여기에 몇 가지 스코프 변수도 삽입하겠습니다. 예를 들어 디렉티브에서 할 수 있는 것과 같습니다.이러한 변수를 함수 인수로 명시적으로 전달할 필요 없이 이를 수행할 수 있습니까?

그럴 수 있는 모양이다.

일반적으로 스코프 변수를 함수 파라미터로 필터에 전달합니다.

function MyCtrl($scope){
  $scope.currentDate = new Date();
  $scope.dateFormat = 'short';
}
<span ng-controller="MyCtrl">{{currentDate | date:dateFormat}}</span> // --> 7/11/13 4:57 PM

하지만 현재 스코프를 통과하려면this:

<span ng-controller="MyCtrl">{{currentDate | date:this}}</span>

그리고.this현재 범위에 대한 참조가 됩니다.

심플화:

app.controller('AppController',
    function($scope) {
      $scope.var1 = 'This is some text.';
      $scope.var2 = 'And this is appended with custom filter.';
    }
  );
  

app.filter('filterReceiptsForDate', function () {
  return function (input, scope) {
    return input + ' <strong>' + scope.var2 + '</strong>';
  };
});
<div ng-bind-html-unsafe="var1 | filterReceiptsForDate:this"></div>
<!-- Results in: "This is some text. <strong>And this is appended with custom filter.</strong>" -->

PLUNKER

경고:

  1. 이 점에 주의해 주세요.필터 내부의 값을 읽기 위해서만 스코프를 사용합니다.그렇지 않으면 $digest 루프에서 자신을 쉽게 찾을 수 있습니다.
  2. 이러한 「중대한」의존성(범위 전체)을 필요로 하는 필터는, 테스트하기 매우 어려운 경향이 있습니다.

나는 그것을 발견했다.this참조 로컬$scope. 이 방법이 안전한지 확실하지 않습니다.

언급URL : https://stackoverflow.com/questions/17596246/access-scope-variables-from-a-filter-in-angularjs