SoFunction
Updated on 2025-04-13

Detailed explanation of custom command examples

This article describes custom instructions. Share it for your reference, as follows:

Call the method, pass in the instruction name and factory function, and return an object.

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

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

Return to the chained function

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>AngularJS Demo</title>
  <link rel="stylesheet" href="../css/" rel="external nofollow" />
  <link rel="stylesheet" href="../css/" rel="external nofollow" >
  <script src="../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 = ('myApp', [])
  .controller('myCtrl', ["$scope", function ($scope) {
    $ = [
      { 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( (data) ){
        for(var i=0, len=; i<len; i++){
          (data[i].name);
        }
      }
    };
  });
</script>
</html>

Break the dependence on data attributes

Set an element attribute to dynamically set the keys that need to participate in the operation. If the attribute name is prefixed with data-, AngularJS removes this prefix when generating the attribute collection passed to the connection function. In other words, both data-list-property and list-property are represented as listProperty.

<div unordered-list="products" list-property="name"></div>
var data = scope[attrs['unorderedList']];
var propertyName = attrs['listProperty'];
if((data)){
  var listElem = ("<ul>");
  (listElem);
  for(var i=0, len=; i<len; i++){
    ( ('<li>').text(data[i][propertyName]) );
  }
}

Calculate expressions

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

After adding the filter, the custom directive is broken. You can have the scope calculate the attribute value as an expression. scope.$eval() receives two parameters: the expression to be calculated and any local data to be used to perform the calculation.

( ('<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>
$ = function () {
  for(var i=0,len = $; i<len; i++){
    $[i].price++;
  }
}

Add a listener

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

The first function (listener function) calculates a value based on the data in the scope, which is called each time the scope changes. If the return value of the function changes, the processing function will be called, and this process is like a string expression. Provide a function to listen, able to calmly face the situation where data that may have filters in the expression are worthwhile.

The second listener function is for$eval()The expression changes are calculated to execute the callback function.

The above code cannot be displayed correctly, and it involves the for loop closure problem.

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

or

(function (i) {
  var itemElem = ('<li>');
  (itemElem);
  var watchFn = function (watchScope) {
    return watchScope.$eval(propertyName, data[i]);
  };
  scope.$watch(watchFn, function (newValue, oldValue) {
    (newValue);
  });
})(i);

jqLite

jqLiteelement()append()The parameters of the methods such as the HTML string or DOMElement.

return function (scope, element, attrs) {
  var listElem = ("<ol>");
  for (var i = 0; i < ; i++) {
    ("<li>").append("<span>").text([i]);
  }
}

The above added string, and only the last message was added in the end.

return function (scope, element, attrs) {
  var listElem = ("<ol>");
  (listElem);
  for (var i = 0; i < ; i++) {
    (("<li>")
        .append(("<span>").text([i])));
  }
}

For more information about AngularJS, readers who are interested in view the topic of this site:Summary of AngularJS command operation skills》、《AngularJS Introduction and Advanced Tutorial"and"AngularJS MVC architecture summary

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