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


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

查看所有标签

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

Graph Algorithms

Graph Algorithms

Shimon Even / Cambridge University Press / 2011-9-19 / USD 32.99

Shimon Even's Graph Algorithms, published in 1979, was a seminal introductory book on algorithms read by everyone engaged in the field. This thoroughly revised second edition, with a foreword by Richa......一起来看看 《Graph Algorithms》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

在线进制转换器
在线进制转换器

各进制数互转换器