Detailed explanation of Angular1.x custom instruction instance

  • 2021-07-26 06:01:27
  • OfStack

This article illustrates the Angular1. x custom directive. Share it for your reference, as follows:

Call the Module. directive method, pass in the instruction name and factory function, and return 1 object.

Each capital letter in the instruction name is considered to be a separate word in the attribute name, and each word is separated by a hyphen.


var myApp = angular.module('myApp', [])
  .directive("unorderedList", function () {
    return function(scope, element, attrs) {
    };
  });

Returns a chain function


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>AngularJS Demo</title>
  <link rel="stylesheet" href="../css/bootstrap.css" rel="external nofollow" />
  <link rel="stylesheet" href="../css/bootstrap-theme.css" rel="external nofollow" >
  <script src="../js/angular.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
  <div class="panel panel-default">
    <div class="panel-heading">
      <h3>Products</h3>
    </div>
    <div class="panel-body">
      <div unordered-list="products"></div>
    </div>
  </div>
</body>
<script>
var myApp = angular.module('myApp', [])
  .controller('myCtrl', ["$scope", function ($scope) {
    $scope.products = [
      { name: "Apples", category: "Fruit", price: 1.20, expiry: 10 },
      { name: "Bananas", category: "Fruit", price: 2.42, expiry: 7 },
      { name: "Pears", category: "Fruit", price: 2.02, expiry: 6 }
    ];
  }])
  .directive("unorderedList", function () {
    return function (scope, element, attrs) {
      var data = scope[attrs['unorderedList']];
      if( angular.isArray(data) ){
        for(var i=0, len=data.length; i<len; i++){
          console.log(data[i].name);
        }
      }
    };
  });
</script>
</html>

Break the dependence on data attributes

Set 1 element attribute to dynamically set the key to participate in the operation. If the property name is prefixed with data-, AngularJS removes the 1 prefix when generating the property collection passed to the join function. That is, data-list-property and list-property are both denoted as listProperty.


<div unordered-list="products" list-property="name"></div>

var data = scope[attrs['unorderedList']];
var propertyName = attrs['listProperty'];
if(angular.isArray(data)){
  var listElem = angular.element("<ul>");
  element.append(listElem);
  for(var i=0, len=data.length; i<len; i++){
    listElem.append( angular.element('<li>').text(data[i][propertyName]) );
  }
}

Evaluate expression


<div unordered-list="products" list-property="price | currency"></div>

After adding the filter, the custom instruction is destroyed. You can have the scope evaluate the property value as if it were an expression. scope. $eval () takes two parameters: the expression to evaluate and any local data needed to perform the evaluation.


listElem.append( angular.element('<li>').text(scope.$eval(propertyName, data[i])) );

Handle data changes


<div class="panel-body">
  <button class="btn btn-primary" ng-click="incrementPrices()">
    Change Prices
  </button>
</div>

$scope.incrementPrices = function () {
  for(var i=0,len = $scope.products.length; i<len; i++){
    $scope.products[i].price++;
  }
}

Add a listener


if(angular.isArray(data)){
  var listElem = angular.element("<ul>");
  element.append(listElem);
  for(var i=0, len=data.length; i<len; i++){
    var itemElem = angular.element('<li>');
    listElem.append(itemElem);
    var watchFn = function (watchScope) {
      return watchScope.$eval(propertyName, data[i]);
    };
    scope.$watch(watchFn, function (newValue, oldValue) {
      itemElem.text(newValue);
    });
  }
}

The first function (the listener function) calculates a value based on the data in the scope and is called every time the scope changes. If the return value of the function changes, the handler is called, just like String Expression Mode 1. Provides a function to listen, and can calmly face the situation that the data value in the expression may have filters.

The second listener function is for the $eval() Calculate the expression change to execute the callback function.

The above code is not displayed correctly, which involves for loop closure.


for(var i=0, len=data.length; i<len; i++){
  (function () {
    var itemElem = angular.element('<li>');
    listElem.append(itemElem);
    var index = i;
    var watchFn = function (watchScope) {
      return watchScope.$eval(propertyName, data[index]);
    };
    scope.$watch(watchFn, function (newValue, oldValue) {
      itemElem.text(newValue);
    });
  }());
}

Or


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>AngularJS Demo</title>
  <link rel="stylesheet" href="../css/bootstrap.css" rel="external nofollow" />
  <link rel="stylesheet" href="../css/bootstrap-theme.css" rel="external nofollow" >
  <script src="../js/angular.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
  <div class="panel panel-default">
    <div class="panel-heading">
      <h3>Products</h3>
    </div>
    <div class="panel-body">
      <div unordered-list="products"></div>
    </div>
  </div>
</body>
<script>
var myApp = angular.module('myApp', [])
  .controller('myCtrl', ["$scope", function ($scope) {
    $scope.products = [
      { name: "Apples", category: "Fruit", price: 1.20, expiry: 10 },
      { name: "Bananas", category: "Fruit", price: 2.42, expiry: 7 },
      { name: "Pears", category: "Fruit", price: 2.02, expiry: 6 }
    ];
  }])
  .directive("unorderedList", function () {
    return function (scope, element, attrs) {
      var data = scope[attrs['unorderedList']];
      if( angular.isArray(data) ){
        for(var i=0, len=data.length; i<len; i++){
          console.log(data[i].name);
        }
      }
    };
  });
</script>
</html>

0

jqLite

In jqLite element() , append() HTML string or DOMElement.


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>AngularJS Demo</title>
  <link rel="stylesheet" href="../css/bootstrap.css" rel="external nofollow" />
  <link rel="stylesheet" href="../css/bootstrap-theme.css" rel="external nofollow" >
  <script src="../js/angular.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
  <div class="panel panel-default">
    <div class="panel-heading">
      <h3>Products</h3>
    </div>
    <div class="panel-body">
      <div unordered-list="products"></div>
    </div>
  </div>
</body>
<script>
var myApp = angular.module('myApp', [])
  .controller('myCtrl', ["$scope", function ($scope) {
    $scope.products = [
      { name: "Apples", category: "Fruit", price: 1.20, expiry: 10 },
      { name: "Bananas", category: "Fruit", price: 2.42, expiry: 7 },
      { name: "Pears", category: "Fruit", price: 2.02, expiry: 6 }
    ];
  }])
  .directive("unorderedList", function () {
    return function (scope, element, attrs) {
      var data = scope[attrs['unorderedList']];
      if( angular.isArray(data) ){
        for(var i=0, len=data.length; i<len; i++){
          console.log(data[i].name);
        }
      }
    };
  });
</script>
</html>

1

What was added above is a string, and only the last message in scope. names was added at last.


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>AngularJS Demo</title>
  <link rel="stylesheet" href="../css/bootstrap.css" rel="external nofollow" />
  <link rel="stylesheet" href="../css/bootstrap-theme.css" rel="external nofollow" >
  <script src="../js/angular.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
  <div class="panel panel-default">
    <div class="panel-heading">
      <h3>Products</h3>
    </div>
    <div class="panel-body">
      <div unordered-list="products"></div>
    </div>
  </div>
</body>
<script>
var myApp = angular.module('myApp', [])
  .controller('myCtrl', ["$scope", function ($scope) {
    $scope.products = [
      { name: "Apples", category: "Fruit", price: 1.20, expiry: 10 },
      { name: "Bananas", category: "Fruit", price: 2.42, expiry: 7 },
      { name: "Pears", category: "Fruit", price: 2.02, expiry: 6 }
    ];
  }])
  .directive("unorderedList", function () {
    return function (scope, element, attrs) {
      var data = scope[attrs['unorderedList']];
      if( angular.isArray(data) ){
        for(var i=0, len=data.length; i<len; i++){
          console.log(data[i].name);
        }
      }
    };
  });
</script>
</html>

2

More readers interested in AngularJS can check the topics of this site: "Summary of AngularJS Instruction Operation Skills", "Introduction and Advanced Tutorial of AngularJS" and "Summary of AngularJS MVC Architecture"

I hope this article is helpful to everyone's AngularJS programming.


Related articles: