directive是一个非常棒的功能。可以实现我们自义的的功能方法。下面通过实例代码给大家介绍angularjs自定义指令directive相关知识,感兴趣的朋友一起学习吧
今天学习angularjs自定义指令Directive。
Directive是一个非常棒的功能。可以实现我们自义的的功能方法。
下面的例子是演示用户在文本框输入的帐号是否为管理员的帐号"Admin"。
在网页上放一个文本框和一个铵钮:

<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>
@Scripts.Render("~/bundles/angular")定义一个App:
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;
}
}
};
});演示:

以上就是关于Angularjs的自定义指令Directive的具体介绍的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号