Angularjs笔记(五)

自定义指令

<!DOCTYPE HTML>
<html ng-app="myApp">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<script src="angular.min.js"></script>
<style>
#div1 div,#div2 div{ width:200px; height:200px; border:1px red solid; display:none;}
#div1 input.active , #div2 input.active{ background:red;}
</style>
<script>
   var m1=angular.module("myApp",[]);
   m1.directive("myTab",function(){
         return{
             restrict:"AECM",//A--属性,E--元素,C--样式类,M--注释(要大写)
             replace:true,//覆盖模板
transclude : true,//阻止嵌套元素被template覆盖
//scope:true,//独立作用域 scope:{//隔离作用域,只在当前标签下起作用,外面访问不到 myId:"@myId",//@普通的字符串,也可去掉myId因为他跟键相同 myName:"=",//=是获取controller的数据 myFn:"&"//&父级函数 },//里面的@=&叫做绑定策略,这里是不共享的 controller:["$scope",function($scope){ $scope.name="miaov"; }],//这里的数据是共享的 //template : '<div>hello angular</div>'//要显示的内容 templateUrl:'temp2.html',//模板路径 link:function(scope,element,attr,reController){//link是进行dom操作的,按收四个参数 //scope 作用域,找到上面的name值scope.name miaov //element 最外层的元素 //attr 对应的属性 } } }); m1.controller("Aaa",["$scope",function($scope){ $scope.name="hello"; $scope.show=function(n){ alert(n); } }]); </script> </head> <body ng-controller="Aaa"> <my-tab my-id="div1" my-name="name" my-fn="show(num)"></my-tab> <my-tab my-id="div2" my-name="name" my-fn="show(num)"></my-tab> </body> </html>

-----temp2.html-----

<div id="{{myId}}">
<input class="active" type="button" value="1" ng-click="myFn({num:456})">
<input type="button" value="2">
<input type="button" value="3">
<div style="display:block">{{name}}</div>
<div>22222222</div>
<div>33333333</div>
</div>

 

<!DOCTYPE HTML>
<html ng-app="myApp">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<script src="angular.min.js"></script>
<script>
var m1 = angular.module('myApp',[]);
m1.directive('hello',function(){
    return {
        restrict : 'E',   
        replace : true,
        transclude : true,
        controller : function($scope){
            //$scope.name = 'miaov';
            this.name = 'miaov';
            this.show = function(){};
        },
        template : '<div>hello angular<h1 ng-transclude></h1></div>'
    };
});
m1.directive('hi',function(){
    return {
        restrict : 'E',   
        replace : true,
        require : '?^hello',//require是在两个元素的数据进行转递,上面的controller里不能是$scope要改成this,要获取hello元素对应的东西就要
//在link里拿到reController
//^这个符号是向上获取?是容错处理,如果没有也不会出现一大堆报错
template :
'<span>hi angular</span>', link : function(scope,element,attr,reController){ console.log( reController ); } }; }); m1.controller('Aaa',['$scope',function($scope){ }]); </script> </head> <body ng-controller="Aaa"> <hello> <hi></hi> </hello> </body> </html>

 

posted @ 2015-10-21 16:07  Mi文  阅读(123)  评论(0编辑  收藏  举报