0

J started learn Angular and I have trouble with getting value of checkboxes.

<label ng-repeat="role in groupsapp">
<input type="checkbox" ng-click="selectedRole([role.name,role.id,????])">{{role.name}}</label>

How get value checked/unchecked in place "???" I found also:

ng-true-value="{{role.id}}_{{role.name}}_true"
ng-false-value="{{role.id}}_{{role.name}}_false"

but I don't know how to get this value of checkbox, anyone can help ?

1
  • Just put a value="1" or whatever you would like as a value, the checkbox value will be either blank or this value when checked Commented Oct 26, 2016 at 22:56

2 Answers 2

1

to get it working with angular you need to add the ng-model directive to your input so angular will process it.

<label ng-repeat="role in groupsapp">
    <input ng-model="role.value" type="checkbox" ng-click="selectedRole([role.name,role.id,role.value])">{{role.name}}
</label>
Sign up to request clarification or add additional context in comments.

2 Comments

I don't have role.value - value ? Where can I get it ? Its now - "undefined"
Did you add ng-model="role.value"? If you did and if role is an object then it should set the value to it
0

I guess you might have got your answer but still if in case in future if you want to use multiple check boxes and need to collect what all items are collected you can use a custom directive.Here is a link on how to use it.

Below is sample code snippet in HTML

<body ng-app="mainApp" ng-controller="MainCtrl">
 <h1>Multi Check box</h1>
 <multi-checkbox selectedlist="req.selectedList" orginallist="req.sourceList" value="code" label="desc" all="true" sort-by="desc"></multi-checkbox>
 <pre ng-cloak>{{req.selectedList |json}}</pre>
</body>

This requires a source list(orginallist) and a destination list(selectedlist) where selected values should go,it also sorts the list as per your need.

Just add this directive in your JS file

mainApp.directive('multiCheckbox', ['$log', '$filter', '$timeout', function($log, $filter, $timeout) {

    return {

        restrict: 'EA',//E-element & A - attribute

        template:

            '<div> <div ng-show="checkbox.showAll" class="checkbox"> ' +

            '<label style="font-size: 12px"> <input type="checkbox" ' +

            'id="all" name="all" ng-model="checkbox.all" ' +

            'ng-checked="checkbox.all" ng-change="selectAll()" /> All ' +

            '</label> ' +

            '</div>' +

            '<div ng-repeat="item in list  track by $index "class="checkbox"> ' +

            '<label style="font-size: 12px"> <input type="checkbox" ' +

            'id="{{item.value}}" name="{{item.label}}"  ' +

            'ng-checked="item.checked" ng-click="$parent.toggle($index)"/> {{item.label}}' +

            '</label>' +

            '</div> </div>',

        replace: true,  //to replace our custom template in place of tag <multi-checkbox>

        transclude: false,//make it true if we want to insert anything  btw directive tags

        scope: {  //isolate scope created 

            selectedlist: '=',

            orginallist: '=',

            value: '@',

            label: '@',

            all: '@',

            sortBy: '@'

        },

        link: function($scope, element, attrs) {

            $scope.checkbox = {};

            $scope.checkbox.all = false; //set 'All' checkbox to false

            $scope.checkbox.showAll = $scope.all == 'true' ? true : false;//to show/hide 'All' checkbox

            //function called on click of check box
            $scope.toggle = function(index) {

                var item = $scope.list[index];

                var i = $scope.selectedlist.length > 0 ? $scope.selectedlist.indexOf(item.value) : -1;

                item.checked = !item.checked;

                if (!item.checked) {

                    $scope.selectedlist.splice(i, 1);//remove item if unchecked

                    $scope.checkbox.all = false;//make 'All' to uncheck too

                } else if (item.checked) {

                    $scope.selectedlist.push(item.value);//add item if checked

                }

            };

            //function called when 'All' checkbox is checked
            $scope.selectAll = function() {

                var totalList = $scope.list;

                $scope.selectedlist = [];

                //if selected add all items 
                //if unchecked remove all items from selected list
                angular.forEach(totalList, function(item) {

                    item.checked = $scope.checkbox.all;

                    if (item.checked) {

                        $scope.selectedlist.push(item.value);

                    } else {

                        $scope.selectedlist = [];

                    }

                });

            };


            //always watch my source list if it has been modified and update back..
            $scope.$watch('orginallist', function(value) {

                //sort accordingly..
                value = $filter('orderBy')(value, $scope.sortBy);

                $scope.list = [];

                if (angular.isArray(value)) {

                    angular.forEach(value, function(item) {

                        $scope.list.push({

                            value: item[$scope.value],

                            label: item[$scope.label],

                            checked: item.checked

                        });

                    });

                }

            }, true);


            //clear 'All' checkbox value if all items are de selected
            $scope.$watch('selectedlist', function(value) {

                if (!angular.isArray(value) || (angular.isArray(value) && value.length <= 0)) {

                    $scope.checkbox.all = false;

                }

            }, true);
        }

    };

}]);

3 Comments

This solution seems a bit bloated to me, when angular already provides the nessesery tools for the job. It's always nice to show that you can write your own directives, but the angular team has spent a lot of time and man power writing the built in directives, and people don't seem to use them as much as they maybe could. Plus if you were going to do it like that, with 2 arrays for selected or unselected values, you should define the arrays as value services, so they can be injected into other services, directives or controllers.
Dude ! Did you even understand the answer ? It's about avoiding redundant code ..by writing custom directives . Here the both lists are injected from controller itself anyone using this directive can have their own set of list objects and they can access them always to manipulate. And what are you talking about Angular directives ? Do you think I don't know ? Check out my resume and I m not Kidding here . What angular directive is providing this support of multiple check box functionality ? Did you go through the link provided their in solution ?
calm down buddy, im not saying it wont work, or that it isnt an answer to the question, its just a bit much, i dont think thats any sort of attack against your code, but i will say that it seems a bit novice ./ uninformed to plug a huge string like that into the directives template attribute, thats for small strings, for something that size your better off using the $templateCache service and putting the template into a script tag with its type set to text/ng-template, more readable, less prone to error and less plus symbols, all positives.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.