首页 > 编程 > JavaScript > 正文

Angular1.x自定义指令实例详解

2019-11-19 17:22:35
字体:
来源:转载
供稿:网友

本文实例讲述了Angular1.x自定义指令。分享给大家供大家参考,具体如下:

调用Module.directive方法,传入指令名称和工厂函数,返回一个对象。

指令名称中每个大写字母会被认为是属性名中的一个独立的词,而每个词之间是以一个连字符分隔的。

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

返回链式函数

<!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>

打破对数据属性的依赖

设置一个元素属性,用来动态第设置需要参加运算的键。如果属性名是以data-为前缀的,AngularJS会在生成传给连接函数的属性集合时移除这一前缀。也就是说data-list-property和list-property都会被表示为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]) );  }}

计算表达式

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

添加过滤器后,自定义指令被破坏了。可以让作用域将属性值当做一个表达式进行计算。scope.$eval()接收两个参数:要计算的表达式和需要用于执行该计算的任意本地数据。

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

处理数据变化

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

添加监听器

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

第一个函数(监听器函数)基于作用域中的数据计算出一个值,该函数在每次作用域发生变化时都会被调用。如果该函数的返回值发生了变化,处理函数就会被调用,这个过程就像字符串表达式方式一样。提供一个函数来监听,能够从容地面对表达式中有可能带有过滤器的数据值得情形。

第二个监听器函数是针对$eval()计算的表达变化,来执行回调函数的。

以上代码并不能正确显示,涉及到for循环闭包问题。

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

或者

(function (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);  });})(i);

jqLite

jqLite中element()append()等方法的参数是HTML string or DOMElement。

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

上述添加的是字符串,最后添加只有scope.names中最后一条信息。

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

更多关于AngularJS相关内容感兴趣的读者可查看本站专题:《AngularJS指令操作技巧总结》、《AngularJS入门与进阶教程》及《AngularJS MVC架构总结

希望本文所述对大家AngularJS程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表