AngularJS 0004:模型

随着博主第一次在WPF中接触了绑定,后来不管做CS还是BS总有一种绑定的思维,控件和值的互相绑定。
anjularjs使用ng-model命令来完成绑定的。

绑定

如下
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/angular.min.js"></script>
</head>
<body>
    <div ng-app="myProgram" ng-controller="myCtrl">
        召唤师名称: <input ng-model="name">
    </div>


    <script>
        var app = angular.module('myProgram', []);
        app.controller('myCtrl', function ($scope) {
            $scope.name = "虚空之眼";
        });
</script>
</body>
</html>
效果



双向绑定
上面的绑定是单向绑定,即绑定提前赋值的一个变量。
也可以进行双向绑定,随时前台输入改变界面上的显示的值,比如
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/angular.min.js"></script>
</head>
<body>
    <!--双向绑定-->
    <div ng-app="myProgram" ng-controller="myCtrl">
    您的昵称: <input ng-model="name">
    <h1>你输入了: {{name}}</h1>
    <script>
        var app = angular.module('myProgram', []);
        app.controller('myCtrl', function ($scope) {
            $scope.name = "我只打上单";
        });
</script>


</div>
</body>
</html>
效果



验证输入
验证输入,使用 ng-show命令,当它的属性值返回true,则显示指定的信息。
如下
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/angular.min.js"></script>
</head>
<body>
    <!--验证输入-->
    <form ng-app="" name="myForm">
    日期:
    <input type="time" name="myTel" ng-model="text">
    <span ng-show="myForm.myTel.$error.time">日期不正确</span>
</form>


</body>
</html>
效果




应用状态
ng-model 指令可以为应用数据提供状态值(invalid, dirty, touched, error):
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/angular.min.js"></script>
</head>
<body>


    <!--应用状态-->
    <form ng-app="" name="myProgram" ng-init="myContent = '[email protected]'">
    Email:
    <input type="email" name="myMail" ng-model="myContent" required></p>
    <h1>状态</h1>
    {{myProgram.myMail.$valid}}
    {{myProgram.myMail.$dirty}}
</form>


</body>
</html>
效果




CSS 类
ng-model 指令基于它们的状态为 HTML 元素提供了 CSS 类:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/angular.min.js"></script>
    <style>
input.ng-invalid {
    background-color: darkgreen;
}
</style>
</head>
<body>
    <!--CSS类-->
    <form ng-app="" name="myProgram">
    输入你的名字:
    <input name="myName" ng-model="myText" required>


    </form>


</body>
</html>

效果



工程下载:http://download.csdn.net/detail/yysyangyangyangshan/9697147

猜你喜欢

转载自blog.csdn.net/yysyangyangyangshan/article/details/53396331