angularjs自定义指令Directive

栏目: 编程语言 · AngularJS · 发布时间: 8年前

内容简介:angularjs自定义指令Directive

今天学习angularjs自定义指令Directive。

Directive是一个非常棒的功能。可以实现我们自义的的功能方法。

下面的例子是演示用户在文本框输入的帐号是否为管理员的帐号"Admin"。

在网页上放一个文本框和一个铵钮:

angularjs自定义指令Directive

<form id="form1" name="form1" ng-app="app" ng-controller="ctrl" novalidate>
        <input id="Text1" type="text" ng-model="Account" is-Administrator/>
        <br />
        <input id="ButtonVerify" type="button" value="Verify" ng-click="Verify();" />
    </form>

Source Code

然后你需要引用angularjs的类库:

 @Scripts.Render("~/bundles/angular")

以上是ASP.NET MVC bundle了。

定义一个App:

 var app = angular.module('app', []);

定义一个控制器:

angularjs自定义指令Directive

app.controller('ctrl', function ($scope) {
            $scope.Account;

            $scope.Verify = function () {
                if ($scope.form1.$valid) {
                    alert('OK.');
                }
                else {
                    alert('failure.');
                }
            };
        });          

Source Code

下面是重点代码,自定义指令:

angularjs自定义指令Directive

app.directive("isAdministrator", function ($q, $timeout) {
            var adminAccount = "Admin";

            var CheckIsAdministrator = function (account) {
                return adminAccount == account ? true : false;
            };

            return {
                restrict: "A",
                require: "ngModel",
                link: function (scope, element, attributes, ngModel) {
                    ngModel.$asyncValidators.isAdministrator = function (value) {
                        var defer = $q.defer();
                        $timeout(function () {
                            if (CheckIsAdministrator(value)) {
                                defer.resolve();
                            } else {
                                defer.reject();
                            }
                        }, 700);
                        return defer.promise;
                    }
                }
            };
        });

Source Code

演示:

angularjs自定义指令Directive


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Using Google App Engine

Using Google App Engine

Charles Severance / O'Reilly Media / 2009-5-23 / USD 29.99

With this book, you can build exciting, scalable web applications quickly and confidently, using Google App Engine - even if you have little or no experience in programming or web development. App Eng......一起来看看 《Using Google App Engine》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具