Home  >  Article  >  Web Front-end  >  AngularJS单选框及多选框实现双向动态绑定_AngularJS

AngularJS单选框及多选框实现双向动态绑定_AngularJS

WBOY
WBOYOriginal
2016-05-16 15:20:041377browse

在AngularJS中提及双向数据绑定,大家肯定会想到ng-model指令。

一、ng-model

ng-model指令用来将input、select、textarea或自定义表单控件同包含它们的作用域中的属性进行绑定。它将当前作用域中运算表达式的值同给定的元素进行绑定。如果属性不存在,它会隐式创建并将其添加到当前作用域中。
始终用ng-model来绑定scope上一个数据模型内的属性,而不是scope上的属性,这可以避免在作用域或后代作用域中发生属性覆盖!

<input type="text" ng-model="modelName.somePrototype" />

二、type=”radio”

通过 value 属性指定选中状态下对应的值,并通过 ng-model 将单选框与 $scope 中的属性对应,便实现了 type=”radio” 时的双向动态绑定。

<input type="radio" name="sex" value="male" ng-model="person.sex" />男
<input type="radio" name="sex" value="female" ng-model="person.sex" />女

三、type=”checkbox”

通过AngularJS 的内置指令 ng-true-value 和 ng-false-value ,指定多选框在选中和未选中状态下对应的值,再通过ng-model 将其与 $scope 中的属性对应,便实现了type=”checkbox” 的双向动态绑定。

<input type="checkbox" ng-true-value="true" ng-false-value="false" ng-model="person.like.pingpong" />乒乓球
<input type="checkbox" ng-true-value="true" ng-false-value="false" ng-model="person.like.football" />足球
<input type="checkbox" ng-true-value="true" ng-false-value="false" ng-model="person.like.basketball" />篮球

四、完整示例

<html ng-app="myApp">
<head>
  <meta charset="UTF-8">
  <title>radio & checkbox</title>
  <script type="text/javascript" src="angular.js/1.4.4/angular.min.js"></script>
</head>
<body>
  <input type="radio" name="sex" value="male" ng-model="person.sex" />男
  <input type="radio" name="sex" value="female" ng-model="person.sex" />女
  <input type="text" ng-model="person.sex" />

  <input type="checkbox" ng-true-value="true" ng-false-value="false" ng-model="person.like.pingpong" />乒乓球
  <input type="checkbox" ng-true-value="true" ng-false-value="false" ng-model="person.like.football" />足球
  <input type="checkbox" ng-true-value="true" ng-false-value="false" ng-model="person.like.basketball" />篮球
  <span>{{ person.like.pingpong }} {{ person.like.football }} {{ person.like.basketball }} </span>
</body>
</html>

<script type="text/javascript">
  var app = angular.module('myApp', []);
  app.run(function($rootScope) {
    $rootScope.person = {
      sex: "female",
      like: {
        pingpong: true,
        football: true,
        basketball: false
      }
    };
  });
</script>

以上就是关于AngularJS单选框及多选框实现双向动态绑定的相关介绍,希望对大家的学习有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn