今天学习angularjs自定义指令Directive。
Directive是一个非常棒的功能。可以实现我们自义的的功能方法。下面的例子是演示用户在文本框输入的帐号是否为管理员的帐号"Admin"。在网页上放一个文本框和一个铵钮:@Scripts.Render("~/bundles/angular")
var app = angular.module('app', []);
定义一个控制器:
app.controller('ctrl', function ($scope) { $scope.Account; $scope.Verify = function () { if ($scope.form1.$valid) { alert('OK.'); } else { alert('failure.'); } }; });
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; } } }; });
演示: