angularjs自定义指令Directive

时间:2023-12-26 15:44:49

今天学习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