AngularsJS自定义指令

来源:互联网 发布:阿里云 域名解析设置 编辑:程序博客网 时间:2024/05/29 21:34
<!DOCTYPE html><html><head><meta charset=utf-8><meta name=description content=""><meta name=viewport content="width=device-width, initial-scale=1"><title></title><script src="../js/angular.min.js"></script></head><body ng-app="myApp" >
<!-- 调用--><runoob-directive></runoob-directive><script>var app = angular.module("myApp", []);app.directive("runoobDirective", function() {return {template : "<h2>自定义指令!</h2>"};});</script></body></html>
AngularJS使用 .directive 函数来添加自定义的指令,使用驼峰法来命名一个指令, runoobDirective, 但在使用它时需要以 - 分割, runoob-directive:

AngularJS可以通过以下方式来调用指令:

  • 元素名     <runoob-directive></runoob-directive>
  • 属性 <div runoob-directive></div>
  • 类名 <div class="runoob-directive"></div>
  • 注释 <!-- directive: runoob-directive -->
  • 限制使用方式
通过添加 restrict 属性,并设置只值为 "A", 来设置指令只能通过属性的方式来调用:

restrict 值可以是以下几种:

  • E 作为元素名使用
  • A 作为属性使用
  • C 作为类名使用
  • M 作为注释使用
var app = angular.module("myApp", []);app.directive("runoobDirective", function() {    return {        restrict : "A",        template : "<h1>自定义指令!</h1>"    };});

<body ng-app="myApp" ng-controller="mike"><input type="text" ng-model="name"/><br><second/><script>angular.module('myApp', []).directive('first', [ function(){return {// scope: false, // 默认值,共享父级作用域// controller: function($scope, $element, $attrs, $transclude) {},restrict: 'AE', // E = Element, A = Attribute, C = Class, M = Commenttemplate: 'first name:{{name}}',};}]).directive('second', [ function(){return {scope: true, // 继承父级作用域并创建指令自己的作用域// controller: function($scope, $element, $attrs, $transclude) {},restrict: 'AE', // E = Element, A = Attribute, C = Class, M = Comment//当修改这里的name时,second会在自己的作用域中新建一个name变量,与父级作用域中的// name相对独立,所以再修改父级中的name对second中的name就不会有影响了template: 'second name:{{name}}',};}]).directive('third', [ function(){return {scope: {}, // 创建指令自己的独立作用域,与父级毫无关系// controller: function($scope, $element, $attrs, $transclude) {},restrict: 'AE', // E = Element, A = Attribute, C = Class, M = Commenttemplate: 'third name:{{name}}',};}]).controller('mike', ['$scope', function($scope){$scope.name="张三";}]);</script></body>

1. 当同时调用first和second时,只有first生效,两个template不会同时出现。

2. 当设置了 scope:{} 之后,{{name}}获取不到了,原因就是作用域的问题,想要设置这里的name的值,可以再加一个controller的字段。




原创粉丝点击