使用ng-click和ng-repeat动态创建过滤器

时间:2014-12-30 20:12:19

标签: javascript angularjs angularjs-ng-repeat

现在,我有一堆过滤器使用ng-click过滤从工厂引入的一些JSON数据:

<ul class="brands">
    <li><a href="#" ng-click="brandFilter = null">All</li>
    <li><a href="#" ng-click="brandFilter = { 'manufacturer' : 'Apple' }">Apple</a></li>
    <li><a href="#" ng-click="brandFilter = { 'manufacturer' : 'Samsung' }">Samsung</a></li>
    <li><a href="#" ng-click="brandFilter = { 'manufacturer' : 'HTC' }">HTC</a></li>
</ul>
<div ng-controller="phonesController">
    <div class="phonesContent">
        <article ng-repeat="phones in phoneData | filter:brandFilter" class="phone-article">
            <img src="{{ phones.image }}" alt="{{ phones.name }}" class="phone-img">
            <p>{{ phones.name }}</p>
            <p>Price: ${{ phones.price }}</p>
            <p>No term: ${{ phones.no-term }}</p>
        </article>
    </div>
</div>

它运行良好,但我想知道如何以编程方式生成链接并使用ng-click进行过滤。到目前为止我最好的尝试:

<div ng-controller="phonesController">
    <ul class="brands">
        <li><a href="#" ng-click="brandFilter = null">All</li>
        <li ng-repeat="phones in phoneData | unique: 'manufacturer'"><a href="#" ng-click="brandFilter = { 'manufacturer' = phones.manufacturer }">{{ phones.manufacturer }}</a></li>
    </ul>
    <div class="phonesContent">
        <article ng-repeat="phones in phoneData | filter:brandFilter" class="phone-article">
            <img src="{{ phones.image }}" alt="{{ phones.name }}" class="phone-img">
            <p>{{ phones.name }}</p>
            <p>Price: ${{ phones.price }}</p>
            <p>No term: ${{ phones.no-term }}</p>
        </article>
    </div>
</div>

链接正常生成,数据显示在phonesContent div中,但过滤不起作用。我一直得到一个$ parse:语法错误,所以我的表达式出错了brandFilter = { 'manufacturer' = phones.manufacturer }(我认为)。

1 个答案:

答案 0 :(得分:0)

Rob已经指出了为什么你的代码不起作用,但我想说最好避免在你的指令中使用赋值语句。这样就可以清楚地定义控制器的界面了。

我建议在您的控制器中添加一个范围函数setFilter()来设置过滤器值:

$scope.setFilter = function (value) {
    $scope.brandFilter = value ? { manufacturer: value } : null;
};

然后你可以这样做:

<li><a href="#" ng-click="setFilter(null)">All</li>
<li ng-repeat="phones in phoneData | unique: 'manufacturer'">
<a href="#" ng-click="setFilter(phones.manufacturer)">{{ phones.manufacturer }}</a>
</li>