PHP群:95885625 Hbuilder+MUI群:81989597 站长QQ:634381967
    您现在的位置: 首页 > 开发编程 > AngularJS教程 > 正文

    AngularJS 模型

    作者:admin来源:网络浏览:时间:2020-09-30 00:07:50我要评论
    导读:AngularJSng-model 指令ng-model 指令用于绑定应用程序数据到 HTML 控制器(input, select, textarea)的值。ng-model 指令ng-model指...

    AngularJS ng-model 指令


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


    ng-model 指令

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

    1. <div ng-app="myApp" ng-controller="myCtrl"
    2.     名字: <input ng-model="name"
    3. </div> 
    4.  
    5. <script> 
    6. var app = angular.module('myApp', []); 
    7. app.controller('myCtrl'function($scope) { 
    8.     $scope.name = "John Doe"
    9. }); 
    10. </script> 

     

    双向绑定

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

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

    验证用户输入

    1. <form ng-app="" name="myForm"
    2.     Email: 
    3.     <input type="email" name="myAddress" ng-model="text"
    4.     <span ng-show="myForm.myAddress.$error.email">不是一个合法的邮箱地址</span> 
    5. </form> 

    以上实例中,提示信息会在 ng-show 属性返回 true 的情况下显示。

    应用状态

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

    1. <form ng-app="" name="myForm" ng-init="myText = 'test@runoob.com'"
    2.     Email: 
    3.     <input type="email" name="myAddress" ng-model="myText" required></p> 
    4.     <h1>状态</h1> 
    5.     {{myForm.myAddress.$valid}} 
    6.     {{myForm.myAddress.$dirty}} 
    7.     {{myForm.myAddress.$touched}} 
    8. </form> 

    CSS 类

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

    1. <style> 
    2. input.ng-invalid { 
    3.     background-color: lightblue; 
    4. </style> 
    5. <body> 
    6.  
    7. <form ng-app="" name="myForm"
    8.     输入你的名字: 
    9.     <input name="myAddress" ng-model="text" required> 
    10. </form> 

    ng-model 指令根据表单域的状态添加/移除以下类:

    • ng-empty
    • ng-not-empty
    • ng-touched
    • ng-untouched
    • ng-valid
    • ng-invalid
    • ng-dirty
    • ng-pending
    • ng-pristine
    转载请注明(B5教程网)原文链接:https://b5.mxunkeji.com/content-152-3418-1.html
    相关热词搜索:
    上一篇:AngularJS 指令