ng 指令的自定义使用

Posted 撒哈拉的雪

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ng 指令的自定义使用相关的知识,希望对你有一定的参考价值。

 

1、创建和使用
var app = angular.module(‘myApp‘,[‘ng‘]);
app.directive(‘指令名称‘,func);


自定义指令的命名:
驼峰式,有两部分构成,前缀一般是公司或者项目的缩写,后缀表示的为指令的作用(tsHello)
使用指令时:采用烤串式的方式去使用
(ts-hello)

2、高级

属性:
①template 显示的模板内容
②restrict: ‘EACM‘ (E:元素A:属性C:类M:注释)
作为注释去调用自定义指令时,需要设置replace属性为true
③replace 替换
④scope:接收参数

 

<!DOCTYPE html>
<html ng-app="myModule">
<head lang="en">
  <meta charset="UTF-8">
  <script src="js/angular.js"></script>
  <title></title>
</head>
<body>
<!--控制器的调用-->
<div ng-controller="myCtrl">
  <!-- element-->
  <ts-hello></ts-hello>
  <!-- attribute-->
  <div ts-hello></div>
  <!-- class-->
  <div class="ts-hello"></div>
  <!-- directive: ts-hello -->
</div>

<script>
  //模块的创建
  var app = angular.module(myModule,[ng]);
  //创建控制器
  app.controller(myCtrl, function ($scope) {

  })

  //创建自定义指令
  app.directive(tsHello, function () {
    return {
      template:<h1>Hello Directive</h1>,
//      E:Element A:Atrribute C:Class M:Comment
      restrict:EACM,
      replace:true
    }
  })

</script>
</body>
</html>

 

 

3.调用指令来传递参数并处理:

①在自定义的指令内部去准备接收
指定scope,把要传递过来的值存在驼峰式命名的变量中,指定@,在调用指令传参时,就会读取该属性对应的值
scope:{
testName:‘@‘
}
②传递参数
在调用指令时,指定对应的属性名称和要传递的值
<div test-hello test-name="123"></div>

 

<!DOCTYPE html>
<html ng-app="myApp">
<head lang="en">
  <meta charset="UTF-8">
  <script src="js/angular.js"></script>
  <title></title>
</head>
<body>

<div ng-controller="myCtrl">
  <div ts-hello test-name="world"></div>
</div>
<script>
  var app = angular.module(myApp, [ng]);
//  创建指令并传参
  app.directive(tsHello, function () {
    return {
      template:<span>  +
      Hello {{testName}}</span>,
      scope:{
        testName:@
      }
    }
  })

  app.controller(myCtrl, function () {
    console.log(myCtrl  func is called);
  })
</script>
</body>
</html>

 

<!DOCTYPE html>
<html ng-app="myApp">
<head lang="en">
  <meta charset="UTF-8">
  <script src="js/angular.js"></script>
  <title></title>
</head>
<body>

<div ng-controller="myCtrl">
</div>
<!--调用指令,并通过属性传参-->
<ts-directive ts-name="Hello World"></ts-directive>

<script>
  var app = angular.module(myApp, [ng]);
  //创建指令
  app.directive(tsDirective, function () {
    return{
      template:<h1>{{tsName}}</h1>,
      scope:{
        tsName:@//@取ts-name属性对应的值
      }
    }
  })

  app.controller(myCtrl, function () {
    console.log(myCtrl  func is called);
  })
</script>
</body>
</html>

 

以上是关于ng 指令的自定义使用的主要内容,如果未能解决你的问题,请参考以下文章

AngularJS ng-repeat 与表格内的自定义元素呈现奇怪

通过自定义指令进行 ng-grid 分页

在 AngularJS 应用程序中拖放的自定义指令

ng-click 不会在已编译的模板内触发

找到我的自定义代码片段 Xcode 6?

angular js中的directive