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>

 

转载于:https://www.cnblogs.com/web-fusheng/p/6953504.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值