Wednesday 12 October 2016

Create List of CheckBoxes in AngularJS


This blog will explain you how you can create a list of CheckBoxes to store selected objects of an array in one model. I am using a directive Checklist-model which solves the task with less line of codes in controller.
First you need to download the js for Checklist-model  Press Me

service code :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using MvcApplication1.Models;


namespace MvcApplication1.Controllers
{
    public class ValuesController : ApiController
    {
        [HttpGet]
        public List<EMP> Gets()
        {
            using (Database1Entities obj = new Database1Entities())
            {
                return obj.EMPs.ToList();
            }
        }
    }
}


view code :

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="Scripts/angular.js"></script>
    <script src="Scripts/checklist-model.min.js"></script>

</head>
<body>
    <div ng-app="app">
        <div ng-controller="ctrl">
            <label ng-repeat="c in list">
                <input type="checkbox" checklist-model="selected.emps" checklist-value="c" /> {{c.NAME}}<br />
            </label>
            <button ng-click="selectAll()">Select all</button>
            <button ng-click="deselectAll()">Deselect all</button> <br />
            {{selected.emps}}
        </div>
    </div>
</body>
</html>
<script type="text/javascript">
    angular.module('app', ['checklist-model'])
    .controller('ctrl', function ($scope,$http) {
        function fill()
        {
            $http({
                url: 'http://localhost:53101/api/Values',
                type:'Get'
            }).then(function (d) {
                $scope.list = d.data;
            });
         
        } fill();
     
        $scope.selected = {
            emps: []
        };

     
        $scope.selectAll = function () {
            $scope.selected.emps = angular.copy($scope.list);
        };

     
        $scope.deselectAll = function () {
            $scope.selected.emps = [];
        };
    });
</script>

No comments:

Post a Comment