AngularJS自定义指令

一.restrict属性:


示例:

<!doctype html>
<html ng-app="MyModule">
	<head>
		<meta charset="utf-8">
	</head>
	<body>
		<hello></hello>
		<div hello></div>
		<div class="hello"></div>
		<!-- directive:hello -->
	</body>
	<script src="framework/angular-1.3.0.14/angular.js"></script>
	<script src="HelloAngular_Directive.js"></script>
</html>
var myModule = angular.module("MyModule", []);
myModule.directive("hello", function() {
    return {
        restrict: 'AEMC',
        template: '<div>Hi everyone!</div>',
        replace: true
    }
});
编译为:



二.replace属性
    默认为false,若设置为true,则会移除用户在html中的内容。 

<hello>
    <div>这里是指令内部的内容。</div>
</hello>
var myModule = angular.module("MyModule", []);
myModule.directive("hello", function() {
    return {
    	restrict:"AE",
    	template:"<div>Hello everyone!</div>",
    	replace:true
    } 
});
编译为:


三.$templateCache对象:从浏览器缓存中获得html片段

  示例:

<hello></hello>
var myModule = angular.module("MyModule", []);

//注射器加载完所有模块时,此方法执行一次
myModule.run(function($templateCache){
	$templateCache.put("hello.html","<div>Hello everyone!!!!!!</div>");
});

myModule.directive("hello", function($templateCache) {
    return {
        restrict: 'AECM',
        template: $templateCache.get("hello.html"),
        replace: true
    }
});
编译结果:


四.templateUrl属性

<hello></hello>
var myModule = angular.module("MyModule", []);
myModule.directive("hello", function() {
    return {
        restrict: 'AECM',
        templateUrl: 'hello.html',
        replace: true
    }
});
最后编译的结果为: 用户定义的html片段内容。

五.transclude属性

   若设置为true,则保留用户在html中定义的内容。

   示例:

		<hello>
			<div>这里是指令内部的内容。</div>
		</hello>
var myModule = angular.module("MyModule", []);
myModule.directive("hello", function() {
    return {
    	restrict:"AE",
    	transclude:true,
    	template:"<div>Hello everyone!<div ng-transclude></div></div>"
    } 
});
编译为:


六.directive(指令)与controller(控制器)之间的交互

   示例:

<!doctype html>
<html ng-app="MyModule">
	<head>
		<meta charset="utf-8">
	</head>
	<body>
		<div ng-controller="MyCtrl">
			<loader howToLoad="loadData()">滑动加载</loader>
		</div>
		<div ng-controller="MyCtrl2">
			<loader howToLoad="loadData2()">滑动加载</loader>
		</div>
	</body>
	<script src="framework/angular-1.3.0.14/angular.js"></script>
	<script src="Directive&Controller.js"></script>
</html>
var myModule = angular.module("MyModule", []);
myModule.controller('MyCtrl', ['$scope', function($scope){
	$scope.loadData=function(){
		console.log("加载数据中...");
    }
}]);
myModule.controller('MyCtrl2', ['$scope', function($scope){
    $scope.loadData2=function(){
        console.log("加载数据中...22222");
    }
}]);
myModule.directive("loader", function() {
    return {
    	restrict:"AE",
    	link:function(scope,element,attrs){
    		element.bind('mouseenter', function(event) {
    			//scope.loadData();
    			// scope.$apply("loadData()");
    			// 注意这里的坑,howToLoad会被转换成小写的howtoload
    			scope.$apply(attrs.howtoload);
    		});
        }
    } 
});
将鼠标分别移动到元素上得到结果:


七.directive(指令)之间的交互

   示例:

<!doctype html>
<html ng-app="MyModule">

<head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="css/bootstrap-3.0.0/css/bootstrap.css">
    <script src="framework/angular-1.3.0.14/angular.js"></script>
    <script src="Directive&Directive.js"></script>
</head>

<body>
	<div class="row">
		<div class="col-md-3">
			<superman strength>动感超人---力量</superman>
		</div>
	</div>
	<div class="row">
		<div class="col-md-3">
			<superman strength speed>动感超人2---力量+敏捷</superman>
		</div>
	</div>
	<div class="row">
		<div class="col-md-3">
			<superman strength speed light>动感超人3---力量+敏捷+发光</superman>
		</div>
	</div>
</body>
</html>
var myModule = angular.module("MyModule", []);
myModule.directive("superman", function() {
    return {
        scope: {},   //独立作用域
        restrict: 'AE',
        controller: function($scope) {  //暴露共用的属性和方法
            $scope.abilities = [];
            this.addStrength = function() {
                $scope.abilities.push("strength");
            };
            this.addSpeed = function() {
                $scope.abilities.push("speed");
            };
            this.addLight = function() {
                $scope.abilities.push("light");
            };
        },
        link: function(scope, element, attrs) {  //操作DOM
            element.addClass('btn btn-primary');
            element.bind("mouseenter", function() {
                console.log(scope.abilities);
            });
        }
    }
});
myModule.directive("strength", function() {
    return {
        require: '^superman',
        link: function(scope, element, attrs, supermanCtrl) {
            supermanCtrl.addStrength();
        }
    }
});
myModule.directive("speed", function() {
    return {
        require: '^superman',
        link: function(scope, element, attrs, supermanCtrl) {
            supermanCtrl.addSpeed();
        }
    }
});
myModule.directive("light", function() {
    return {
        require: '^superman',
        link: function(scope, element, attrs, supermanCtrl) {
            supermanCtrl.addLight();
        }
    }
});
将鼠标分别移到相应元素得到结果:


八.独立作用域scope及三种绑定策略

   示例1: 

<hello></hello>
<hello></hello>
<hello></hello>
<hello></hello>
var myModule = angular.module("MyModule", []);
myModule.directive("hello", function() {
    return {
        restrict: 'AE',
        scope:{},   //独立作用域
        template: '<div><input type="text" ng-model="userName"/>{{userName}}</div>',
        replace: true
    }
});


示例2:

<div ng-controller="MyCtrl">
	<drink flavor="{{ctrlFlavor}}"></drink>
</div>
var myModule = angular.module("MyModule", []);
myModule.controller('MyCtrl', ['$scope', function($scope){
	$scope.ctrlFlavor="百威";
}])
myModule.directive("drink", function() {
    return {
    	restrict:'AE',
        scope:{
        	flavor:'@'
        },
        template:"<div>{{flavor}}</div>"
        // ,
        // link:function(scope,element,attrs){
        // 	scope.flavor=attrs.flavor;
        // }
    }
});
最后结果解析为:



示例3:

		<div ng-controller="MyCtrl">
			Ctrl:
			<br>
			<input type="text" ng-model="ctrlFlavor">
			<br>
			Directive:
			<br>
			<drink flavor="ctrlFlavor"></drink>
		</div>
var myModule = angular.module("MyModule", []);
myModule.controller('MyCtrl', ['$scope', function($scope){
	$scope.ctrlFlavor="百威";
}])
myModule.directive("drink", function() {
    return {
    	restrict:'AE',
        scope:{
        	flavor:'='
        },
        template:'<input type="text" ng-model="flavor"/>'
    }
});
解析结果:



示例4:

		<div ng-controller="MyCtrl">
			<greeting greet="sayHello(name)"></greeting>
			<greeting greet="sayHello(name)"></greeting>
			<greeting greet="sayHello(name)"></greeting>
		</div>
var myModule = angular.module("MyModule", []);
myModule.controller('MyCtrl', ['$scope', function($scope){
	$scope.sayHello=function(name){
		alert("Hello "+name);
	}
}])
myModule.directive("greeting", function() {
    return {
    	restrict:'AE',
        scope:{
        	greet:'&'
        },
        template:'<input type="text" ng-model="userName" /><br/>'+
        		 '<button class="btn btn-default" ng-click="greet({name:userName})">Greeting</button><br/>'
    }
});
   



以上部分内容来自慕课网大漠穷秋老师的视频截图

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值