ng-model 指令

ng-model 指令用于绑定应用程序数据到 HTML 控制器(input, select, textarea)的值

ng-model 指令可以将输入域的值与 AngularJS 创建的变量绑定。

就是用来和HTML里面的表单元素绑定。比如 input select 等等

基本绑定示例:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <script src="https://cdn.staticfile.org/angular.js/1.4.6/angular.min.js"></script>
</head>
<body>
    <div ng-app="myApp" ng-controller="myCtrl">
        名字: <input ng-model="name">
    </div>

    <script>
        var app = angular.module('myApp', []);
        app.controller('myCtrl', function ($scope) {
            $scope.name = "John Doe";
        });
    </script>
</body>
</html>Code language: HTML, XML (xml)

双向绑定,在修改输入域的值时, AngularJS 属性的值也将修改:

<body>
    <div ng-app="myApp" ng-controller="myCtrl">
        名字: <input ng-model="name">
        <h1>你输入了: {{name}}</h1>
    </div>

    <script>
        var app = angular.module('myApp', []);
        app.controller('myCtrl', function ($scope) {
            $scope.name = "John Doe";
        });
    </script>
</body>Code language: HTML, XML (xml)

验证用户输入:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <script src="https://cdn.staticfile.org/angular.js/1.4.6/angular.min.js"></script>
</head>
<body>
    <form ng-app="" name="myForm">
        Email:
        <input type="email" name="myAddress" ng-model="text">
        <span ng-show="myForm.myAddress.$error.email">不是一个合法的邮箱地址</span>
    </form>
</body>
</html>Code language: HTML, XML (xml)

应用状态

ng-model 指令可以为应用数据提供状态值(invalid, dirty, touched, error):

<body>
    <form ng-app="" name="myForm" ng-init="myText = 'test@runoob.com'">
        Email:
        <input type="email" name="myAddress" ng-model="myText" required>
        <h1>状态</h1>
        {{myForm.myAddress.$valid}}
        {{myForm.myAddress.$dirty}}
        {{myForm.myAddress.$touched}}
    </form>
</body>Code language: HTML, XML (xml)

CSS 类

ng-model 指令基于它们的状态为 HTML 元素提供了 CSS 类:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <script src="https://cdn.staticfile.org/angular.js/1.4.6/angular.min.js"></script>

    <style>
        input.ng-invalid {
            background-color: orangered;
        }
    </style>
</head>
<body>
    <form ng-app="" name="myForm">
        输入你的名字:
        <input name="myAddress" ng-model="text" required>
    </form>
</body>
</html>Code language: HTML, XML (xml)
Previous:

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注