自定义指令中使用AngularJS扩展HTML的功能。自定义指令使用的“指令”的功能定义。自定义指令只是替换了它被激活的元素。引导过程中AngularJS应用程序找到了匹配的元素,并做好使用自定义指令compile()方法一次活动再处理使用基于指令的范围自定义指令link()方法的元素。 AngularJS提供支持,以下列元素的类型来创建自定义指令。

  •     Element directives - 指令遇到时激活一个匹配的元素。
  •     Attribute - - 指令遇到时激活一个匹配的属性。
  •     CSS - - 指令遇到时激活匹配CSS样式。
  •     Comment - - 指令遇到时激活匹配的注释。

了解自定义指令

定义自定义的HTML标签。

<student name="Mahesh"></student><br/>
<student name="Piyush"></student>

定义自定义指令来处理上面的自定义HTML标签。

var mainApp = angular.module("mainApp", []);

//Create a directive, first parameter is the html element to be attached.  
//We are attaching student html tag. 
//This directive will be activated as soon as any student element is encountered in html
mainApp.directive('student', function() {
  //define the directive object
  var directive = {};
  //restrict = E, signifies that directive is Element directive
  directive.restrict = 'E';
  //template replaces the complete element with its text. 
  directive.template = "Student: <b>{{student.name}}</b> , Roll No: <b>{{student.rollno}}</b>";
  //scope is used to distinguish each student element based on criteria.
  directive.scope = {
    student : "=name"
  }
  //compile is called during application initialization. AngularJS calls it once when html page is loaded.
  directive.compile = function(element, attributes) {
   element.css("border", "1px solid #cccccc");
  //linkFunction is linked with each element with scope to get the element specific data.
   var linkFunction = function($scope, element, attributes) {
     element.html("Student: <b>"+$scope.student.name +"</b> , Roll No: <b>"+$scope.student.rollno+"</b><br/>");
     element.css("background-color", "#ff00ff");
   }
   return linkFunction;
  }
  return directive;
});

定义控制器以更新范围为指令。在这里,我们使用name属性值作为子的作用域。

mainApp.controller('StudentController', function($scope) {
   $scope.Mahesh = {};
   $scope.Mahesh.name = "Mahesh Parashar";
   $scope.Mahesh.rollno = 1;

   $scope.Piyush = {};
   $scope.Piyush.name = "Piyush Parashar";
   $scope.Piyush.rollno = 2;
});

例子

<html>
<head>
  <title>Angular JS Custom Directives</title>
</head>
<body>
  <h2>AngularJS Sample Application</h2>
  <div ng-app="mainApp" ng-controller="StudentController">
 <student name="Mahesh"></student><br/>
 <student name="Piyush"></student>
  </div>
  <script src="/UploadFiles/2021-04-02/angular.min.js">

结果

在Web浏览器中打开textAngularJS.html。看到结果如下:

详解AngularJS中自定义指令的使用

标签:
AngularJS

免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
评论“详解AngularJS中自定义指令的使用”
暂无“详解AngularJS中自定义指令的使用”评论...

P70系列延期,华为新旗舰将在下月发布

3月20日消息,近期博主@数码闲聊站 透露,原定三月份发布的华为新旗舰P70系列延期发布,预计4月份上市。

而博主@定焦数码 爆料,华为的P70系列在定位上已经超过了Mate60,成为了重要的旗舰系列之一。它肩负着重返影像领域顶尖的使命。那么这次P70会带来哪些令人惊艳的创新呢?

根据目前爆料的消息来看,华为P70系列将推出三个版本,其中P70和P70 Pro采用了三角形的摄像头模组设计,而P70 Art则采用了与上一代P60 Art相似的不规则形状设计。这样的外观是否好看见仁见智,但辨识度绝对拉满。