今天學(xué)習(xí)angularjs自定義指令Directive。
Directive是一個(gè)非常棒的功能。可以實(shí)現(xiàn)我們自義的的功能方法。
下面的例子是演示用戶在文本框輸入的帳號(hào)是否為管理員的帳號(hào)"Admin"。
在網(wǎng)頁上放一個(gè)文本框和一個(gè)銨鈕:
<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>
然后你需要引用angularjs的類庫:
@Scripts.Render("~/bundles/angular")
以上是ASP.NET MVC bundle了。
定義一個(gè)App:
var app = angular.module('app', []);
定義一個(gè)控制器:
app.controller('ctrl', function ($scope) { $scope.Account; $scope.Verify = function () { if ($scope.form1.$valid) { alert('OK.'); } else { alert('failure.'); } }; });
下面是重點(diǎn)代碼,自定義指令:
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詳解,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)武林網(wǎng)網(wǎng)站的支持!
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注