onlineracoon
onlineracoon

Reputation: 2970

Angular UI state in combination with service

Basically I have this controller:

angular.controller('AddUsersCtrl', function ($scope, UsersService) {
    $scope.users = [];

    function toggleUser (user) {
        user._toggled = !user._toggled;
    }

    function addAll () 
        var users = $scope.users;

        UsersService
            .addMany(users)
            .success(function (response) {
                // ...
            })
    }
});

It is the controller of a page where users can add multiple users at once, and each users can be toggled (basically it the toggled is the UI state which is used by the view to toggle user information)

But as you can see, the addAll function refers to the users on the scope and then calls a "addMany" method from UsersService. At this point somehow the _toggled variable should be filtered out because else it will also send "_toggled" to the backend.

Now a simple solution would be to loop through the users and remove the "_toggled" variable, but is there a better way or is my structure wrong?

Upvotes: 1

Views: 68

Answers (1)

MarcoS
MarcoS

Reputation: 17721

You could use a separate array for your attribute, like this:

angular.controller('AddUsersCtrl', function ($scope, UsersService) {
    $scope.users = [];
    $scope.toggledUsers = {};

    function toggleUser (user) {
        $scope.toggledUsers[user] = !$scope.toggledUsers[user];
    }

    function addAll () 
        var users = $scope.users;

        UsersService
            .addMany(users)
            .success(function (response) {
                // ...
            })
    }
});

Upvotes: 1

Related Questions