31

私は次の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;
        }
    });

しかし、「item(s)」の代わりに別の単語を使用したいので、フィルターを変更しました

    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>

ただし、$ scopeの変数では機能しません。$scope変数を使用することは可能ですか?

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

ありがとう

4

1 に答える 1

42

はい、から変数を使用することが可能です$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;
        }
     });
于 2013-03-27T14:09:52.387 に答える