Home > Web Front-end > JS Tutorial > A detailed introduction to Angularjs's custom directive Directive

A detailed introduction to Angularjs's custom directive Directive

黄舟
Release: 2017-05-27 10:40:34
Original
1437 people have browsed it

Directive is a great feature. We can implement our own functional methods. The following is an introduction to the knowledge related to AngularjsCustom instruction Directive through example code. Friends who are interested can learn together

Today, learn angularjs custom instruction Directive.

Directive is a great feature. We can implement our own functional methods.

The following example is to demonstrate whether the account entered by the user in the text box is the administrator's account "Admin".

Put a text box and a button on the web page:


##

<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>
Copy after login

Then you need to

cite angularjsClass library:

 @Scripts.Render("~/bundles/angular")
Copy after login

The above is

ASP.NET MVC bundled.

Define an App:

 var app = angular.module(&#39;app&#39;, []);
Copy after login

Define a

Controller:


app.controller(&#39;ctrl&#39;, function ($scope) {
   $scope.Account;
   $scope.Verify = function () {
    if ($scope.form1.$valid) {
     alert(&#39;OK.&#39;);
    }
    else {
     alert(&#39;failure.&#39;);
    }
   };
  });
Copy after login

The following is the key code, custom instructions:


##

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;
     }
    }
   };
  });
Copy after login

Demo:


The above is the detailed content of A detailed introduction to Angularjs's custom directive Directive. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template