AngularJS radio, checkbox

  In project development, it is applied to radio buttons and checkboxes. For Angular, there are actually many implementation methods. The following application examples:

1. AngularJS radio radio example

  There are several project names on the page, and each name has a checkbox in front of it. If it is checked, it means that the project has been completed, and if it is not checked, it means it is not completed.

  Then set an input box below to input the name of the newly added item, and then below it are two radio buttons, only one can be selected to select the completion of the newly added muscle item. At the end is a submit button to add a new item.

        Add Name to Android, select the finished radio button, click the "Add a new item" button, and it will appear in the list above.

<!DOCTYPE html>
<html ng-app="todolist">
<head lang="en">
    <meta charset="UTF-8">
    <title>AngularJS multiple choice</title>
</head>
<body>
<div ng-controller="TodolistController">
    <ul>
        <!--Loop through the items under the scope, ie ($scope.items), and clone this HTML element repeatedly li-->
        <li ng-repeat="item in items">
            <!--When the value of checkbox binding is true, a check mark will be placed on the page-->
            <input type="checkbox" ng-model="item.finished"><span ng-bind="item.name"></span>
        </li>
    </ul>
    <hr>
    <!--A data model name of the bound scope object, this variable gets the content of the input box at any time -->
    Name:<input type="text" ng-model="name">

    <p></p>
    <label>
        <!--
        There are two radio tags, and they must have the same name to achieve the effect of choosing one
        Through different values ​​in ng-value, different radios can be selected to have different values. Then the two radios are bound to the same data model, so that when different radios are selected, the bound data model variables will have different values.
        -->
        <input type="radio" ng-value=true ng-model="state" name="selectState">finished
    </label>
    <label>
        <input type="radio" ng-value=false ng-model="state" name="selectState">unfinished
    </label>

    <!-- This data model is displayed here, in order to test whether its values ​​are correct. can be omitted -->
    <p>{{state}}</p>
    <!--When clicked, execute a function-->
    <button type="button" ng-click="addItem()">Add a new item</button>
</div>
<script src="jquery-1.8.3.js"></script>
<script src="angular1.2.9.js"></script>
<script src="index01.js"></script>
</body>
</html>

index01.js

//Predefine the names of several projects and the status of completion.
var items = [
	{name: 'Javascipt', finished: true},
	{name: 'AngularJS', finished: true},
	{name: 'NodeJS', finished: false},
	{name: 'MongoDB', finished: false}
];
//register a module
var todolistModule = angular.module('todolist', []);
//register a controller
todolistModule.controller('TodolistController', ['$scope', function ($scope) {
	/ / Pass the reference of the surrounding object array to the data model items of the module scope
	$scope.items = items;
	//Initialize the content of the input box to empty
	$scope.name = '';
	//Add function method to scope
	$scope.addItem = function () {
		//Because all objects to be inserted in the future are objects, first define an empty object
		var newItem = {};
		//Assign the values ​​bound in the DOM to the two properties of the newly defined object respectively
		newItem.name = $scope.name;
		newItem.finished = $scope.state;
		// Append the object element at the end of the array
		items.push(newItem);
	};
}]);

 

2. AngularJS determines whether the checkbox/check box is selected and displayed in real time

  Create a function of selecting tags, show some tags to users, and users can choose their favorite tags, which is similar to the filter tags we see on shopping websites. The simple effect is shown in the figure:

index01.html

<!DOCTYPE html>
<html data-ng-app="App">
<head>
	<title>AngularJS radio button</title>
</head>
<body data-ng-controller="AddStyleCtrl">

    <div>Choose Tags</div>    
    <div>
        <div>You have choosen:</div>
        <hr>
        <label data-ng-repeat="selectedTag in selectedTags">
            (({{selectedTag}}))
        </label>
        <hr>
        <div data-ng-repeat="category in tagcategories">
            <div>{{ category.name }}</div>
            <div data-ng-repeat="tag in category.tags">
                <div>
                    <input type="checkbox" id={{tag.id}} name="{{tag.name}}" ng-checked="isSelected(tag.id)" ng-click="updateSelection($event,tag.id)">
                    {{ tag.name }}
                </div>
            </div>
            <hr>
        </div>
    </div>

<pre>{{selected|json}}</pre>
<pre>{{selectedTags|json}}</pre>
</body>
<script src="jquery-1.8.3.js"></script>
<script src="angular1.2.9.js"></script>
<script src="index02.js"></script>
</html>

  <input type="checkbox" id={{tag.id}} name="{{tag.name}}" ng-checked="isSelected(tag.id)" ng-click="updateSelection($event,tag .id)">, which stores the id and name of the tag, uses isSelected(tag.id) to determine whether it is checked, and calls the updateSelection($event, tag.id) method when clicking; if you want the function triggered by ng-click The element that triggers the function cannot be directly passed in this, but needs to be passed in. Because inside, this place is event. Because in Angularjs, the this in this place is scope. We can pass in, then pass event in the function, and then get the element through event.target in the function.

index02.js

var iApp = angular.module("App", []);

iApp.controller('AddStyleCtrl', function($scope)
{
    $scope.tagcategories = [
        {
            id: 1,
            name: 'Color',
            tags: [
                {
                    id:1,
                    name:'color1'
                },
                {
                    id:2,
                    name:'color2'
                },
                {
                    id:3,
                    name:'color3'
                },
                {
                    id:4,
                    name:'color4'
                },
            ]
        },
        {
            id:2,
            name:'Cat',
            tags:[
                {
                    id:5,
                    name:'cat1'
                },
                {
                    id:6,
                    name:'cat2'
                },
            ]
        },
        {
            id:3,
            name:'Scenario',
            tags:[
                {
                    id:7,
                    name:'Home'
                },
                {
                    id:8,
                    name:'Work'
                },
            ]
        }
    ];

    $scope.selected = [];
    $scope.selectedTags = [];

    var updateSelected = function(action,id,name){
        if(action == 'add' && $scope.selected.indexOf(id) == -1){
            $scope.selected.push(id);
            $scope.selectedTags.push(name);
        }
        if(action == 'remove' && $scope.selected.indexOf(id)!=-1){
            var idx = $scope.selected.indexOf(id);
            $scope.selected.splice(idx,1);
            $scope.selectedTags.splice(idx,1);
        }
    }

    $scope.updateSelection = function($event, id){
        var checkbox = $event.target;
        var action = (checkbox.checked?'add':'remove');
        updateSelected(action,id,checkbox.name);
    }

    $scope.isSelected = function(id){
        return $scope.selected.indexOf(id)>=0;
    }
});

  The updateSelection method is called when the checkbox of the html page is clicked. It obtains the clicked DOM element through the $event variable, determines whether it is an add operation or a remove operation through the current state of the checkbox, and then calls the updateSelected method to update the data.

  The isSelected method is used to judge whether the checkbox whose ID is id is selected, and then pass the value to the ng-checked instruction of the page.

  However, I always feel that this implementation method is not in line with the model-centric idea of ​​Angularjs.

 

3. Angularjs implements checkbox all selection, inverse selection

  There is a general checkbox responsible for all selections and inverse selections. When the checkbox is selected at the beginning of each item, the above all selections are automatically selected; when all selections are made, one of the checkboxes is cancelled, and all selections are cancelled.

<!DOCTYPE html>
<html data-ng-app="myApp">
<head>
	<title>AngularJS checded</title>
</head>
<body>
    <div ng-controller="myController">
		<label for="flag">全选
			<input id="flag" type="checkbox" ng-model="select_all" ng-change="selectAll()">
		</label>
		<ul>
			<li ng-repeat="i in list">
				<input type="checkbox" ng-model="i.checked" ng-change="selectOne()">
				<span>{{i.id}}</span>
			</li>
		</ul>
	</div>
</body>
<script src="jquery-1.8.3.js"></script>
<script src="angular1.2.9.js"></script>
<script src="index03.js"></script>
</html>

index03.js

var app = angular.module('myApp',[]);
app.controller('myController', ['$scope', function ($scope) {
    $scope.list = [
        {'id': 101},
        {'id': 102},
        {'id': 103},
        {'id': 104},
        {'id': 105},
        {'id': 106},
        {'id': 107}
    ];
    $scope.checked = [];
    $scope.selectAll = function () {
        if($scope.select_all) {
            $scope.checked = [];
            angular.forEach($scope.list, function (i) {
                i.checked = true;
                $scope.checked.push(i.id);
            })
        }else {
            angular.forEach($scope.list, function (i) {
                i.checked = false;
                $scope.checked = [];
            })
        }
        console.log($scope.checked);
    };
    $scope.selectOne = function () {
        angular.forEach($scope.list , function (i) {
            var index = $scope.checked.indexOf(i.id);
            if(i.checked && index === -1) {
                $scope.checked.push(i.id);
            } else if (!i.checked && index !== -1){
                $scope.checked.splice(index, 1);
            };
        })

        if ($scope.list.length === $scope.checked.length) {
            $scope.select_all = true;
        } else {
            $scope.select_all = false;
        }
        console.log($scope.checked);
    }
}]);

  给数组里面每一个list 绑定checked 的属性。

 

四.利用ngValue

<!DOCTYPE html>
<html data-ng-app="valueExample">
<head>
	<title>AngularJS checded</title>
</head>
<body>
     <form ng-controller="ExampleController">
	   <h2>Which is your favorite?</h2>
		 <label ng-repeat="name in names" for="{{name}}">
			<input type="radio"
				  ng-model="my.favorite"
				  ng-value="name"
				  id="{{name}}"
				  name="favorite">
		   {{name}}
		 </label>
	   <div>You chose {{my.favorite}}</div>
	 </form>
</body>
<script src="jquery-1.8.3.js"></script>
<script src="angular1.2.9.js"></script>
<script src="index04.js"></script>
</html>

index04.js

angular.module('valueExample', [])
	.controller('ExampleController', ['$scope', function($scope) {
		$scope.names = ['pizza', 'unicorns', 'robots', 'jade'];
		$scope.my = { favorite: 'unicorns' };
	}]);

运行效果:



参考文章:

http://blog.csdn.net/lp_frank/article/details/44601283

http://www.cnblogs.com/CheeseZH/p/4517701.html

http://www.cnblogs.com/mayufo/p/5746788.html

https://code.angularjs.org/1.2.32/docs/api/ng/directive/ngValue

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326546974&siteId=291194637
Recommended