programing

Angularjs.변수를 인수로 커스텀필터에 전달하려면 어떻게 해야 하나요?

golfzon 2023. 3. 20. 23:46
반응형

Angularjs.변수를 인수로 커스텀필터에 전달하려면 어떻게 해야 하나요?

다음 HTML을 가지고 있습니다.

<span class="items-count">{{items | countmessage}}</span>

올바른 카운트 메시지를 표시하는 다음 필터

    app.filters
    .filter('countmessage', function () {
        return function (input) {
            var result = input.length + ' item';
            if (input.length != 1) result += 's';
            return message;
        }
    });

하지만 '아이템' 대신 다른 단어를 사용하고 싶어서 필터를 수정했습니다.

    app.filters
    .filter('countmessage', function () {
        return function (input, itemType) {
            var result = input.length + ' ' + itemType;
            if (input.length != 1) result += 's';
            return message;
        }
     });

그런 끈을 사용하면 효과가 있다

<span class="items-count">{{items | countmessage:'car'}}</span>

$syslog 변수에서는 동작하지 않습니다.$syslog 변수를 사용할 수 있습니까?

<span class="items-count">{{items | countmessage:itemtype}}</span>

감사해요.

네, 변수 사용 가능.$scope

예에 대해서는, 다음의 바이올린을 참조해 주세요.http://jsfiddle.net/lopisan/Kx4Tq/

HTML:

<body ng-app="myApp">
    <div ng-controller="MyCtrl">
        <input ng-model="variable"/><br/>
        Live output: {{variable | countmessage : type}}!<br/>
          Output: {{1 | countmessage : type}}!
    </div>
</body>

JavaScript:

var myApp = angular.module('myApp',['myApp.filters']);

function MyCtrl($scope) {
    $scope.type = 'cat';
}

 angular.module('myApp.filters', [])
    .filter('countmessage', function () {
        return function (input, itemType) {
            var result = input + ' ' + itemType;
            if (input >  1) result += 's';
            return result;
        }
     });

언급URL : https://stackoverflow.com/questions/15659559/angularjs-how-can-i-pass-variable-as-argument-to-custom-filter

반응형