在第二个控制器中过滤数组

时间:2015-08-19 09:41:38

标签: angularjs

我试图通过单击controller1中具有id的按钮来过滤Controller2中的数组。这是我到目前为止提出的代码,但我很困惑如何将id参数传递给工厂,过滤列表并更新controller2中的范围。

<div id="parentpage">
    <div ng-controller="ctrl1" id="div1">
        <a href="#" ng-click="buttonclick(1)">Filter list with id 1</a>
        <a href="#" ng-click="buttonclick(2)">Filter list with id 2</a>
    </div>
    <script type="text/javascript">
        angular.bootstrap(document.getElementById('div1'), ['app']);
    </script>

    <div ng-controller="ctrl2" id="div2">
        <ul>
            <li ng-repeat="i in items">{{i.id}}</li>
        </ul>
    </div>
    <script type="text/javascript">
        angular.bootstrap(document.getElementById('div2'), ['app']);
    </script>
</div>

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

app.factory('factory', function($http, $q){
    var factory = {};

    factory.getItems = function() { 
        var deferred = $q.defer();

        $http.get('someRestService').success(function (result){
            deferred.resolve(result);
        })

        return deferred.promise;
    }
});

app.controller('ctrl1', function($scope, factory){
    $scope.buttonclick = function(id) {
        //filter items in ctrl2 based on id
    }
});

app.controller('ctrl2', function($scope, factory){
    $scope.items = factory.getItems();
    $scope.items.then(function (items) {
        $scope.items = items;
    })
});

我该如何做到这一点?

1 个答案:

答案 0 :(得分:0)

您可以创建一个factory,然后可以修改其中$scope中的ctrl2这样的值,如下所示:

<div ng-app="app" id="parentpage">
    <div ng-controller="ctrl1" id="div1"> <a href="#" ng-click="buttonclick(1)">Filter list with id 1</a>
 <a href="#" ng-click="buttonclick(2)">Filter list with id 2</a>
 <a href="#" ng-click="buttonclick()">Clear Filter</a>

    </div>
    <div ng-controller="ctrl2" id="div2">
        <ul>
            <li ng-repeat="i in items()">{{i.id}}</li>
        </ul>
    </div>
</div>

请注意ng-repeat是i in items(),它允许您跟踪工厂中items的更新集。这会运行getItems函数,该函数会从myItems返回factory的值。

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

app.factory('testFactory', function () {
    var myOriginalItems = [{
        id: 1
    }, {
        id: 2
    }, {
        id: 3
    }, {
        id: 4
    }, {
        id: 5
    }];

    var myItems = myOriginalItems;

    return {
        setItems: function (id) {
            if (typeof id == 'undefined') {
                myItems = myOriginalItems;
            } else {
                myItems = [{
                    id: id
                }];
            }
            return myItems;
        },
        getItems: function () {
            return myItems;
        }
    };

});

app.controller('ctrl1', function ($scope, testFactory) {
    $scope.buttonclick = function (id) {
        testFactory.setItems(id);
    };
});

app.controller('ctrl2', function ($scope, testFactory) {
    $scope.items = testFactory.getItems;
});

演示:http://jsfiddle.net/4veqjzdu/