Home  >  Article  >  Web Front-end  >  A detailed introduction to Angularjs’s custom directive Directive

A detailed introduction to Angularjs’s custom directive Directive

黄舟
黄舟Original
2017-05-27 10:40:341276browse

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:


##


Then you need to

cite angularjsClass library:

 @Scripts.Render("~/bundles/angular")

The above is

ASP.NET MVC bundled.

Define an App:

 var app = angular.module('app', []);

Define a

Controller:


app.controller('ctrl', function ($scope) {
   $scope.Account;
   $scope.Verify = function () {
    if ($scope.form1.$valid) {
     alert('OK.');
    }
    else {
     alert('failure.');
    }
   };
  });

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;
     }
    }
   };
  });

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!

Statement:
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