(Study notes) angular custom command

angularjs There are two ways to create custom instructions:

1.module.directive(name,directiveFactory)

2.@see $compileProvider.directive()

var app=angular.module('myApp',[],function($compileProvider){
    	$compileProvider.directive('nameName',function(){
    	
    		//请不要使用ng为指令命名,这样可能会和angular内置指令冲突
    		//如果指令的名字为xxx-yyy,在设置指令的名字时应为xxxYyy驼峰式声明法
    	
        	return{
        		/**
        		自定义指令选项
        		**/
        		};
        	});
        });

指令定义选项:
priority
terminal
scope
controller
controllerAs
require
restrict
template
templateUrl
replace
transclude
compile
link

Detailed customization options:

the restrict : If you ignore restrict, the default is A
If you plan to support ie8, please use the properties and style of instruction based on
E element <name></name>
C style <span class="name"></span>
A property <span name></name>
M Comments <!--directive:name-->
Template
Template: Custom Template content, this content will be based replace parameter setting node or replacement node content.
Example: template:'<div>123</div>'
replace: If this configuration is true then replace elements instruction is located, is false, or if not specified, put the current instruction is added to the elements located inside
Note: it is set to true replace property, because in some cases, custom labels without recognition, i.e. customized labels do not meet the specifications H5
to restrict the element (E) in excess of the final effect, replace all usually set to true

transclude
to be replaced will be added after the tag content label content after replacement
Example:

template:'<div>替换数据 <span ng-transclude></span></div>',
transclude:true

templateUrl
templateUrl: loading the URL template used
to load text / ng-template script id corresponding to the current template
Example:

myApp.directive('customTag',function(){
	return{
		restrict:'ECMA',
		templateUrl:'scriptId',
		replace:true
}
});

Note: When using chrome browser, "same-origin policy" will prevent chrome from file: // load the template, and display a "Access-Control-Allow-Origin" does not permit the source is null, you can put the project into the server load, or Chrome to set a flag, the command is:

chrome-allow-file-access-from-files

There is to pay attention to the conflict and replace property, you want to replace the contents must contain a label that the selection must contain H5 label (for example: <div>content</div>not: content), otherwise it will error

priority
pirority: setting instructions in the execution sequence of the template, relative to other order is executed on the element, the default is 0, in descending order of execution
set a lower priority situations, like ng-repeat, traversing process elements, it is necessary to generate copies of template elements is angular, in other applications instruction, ng-repeat default priority 1000

Terminal
Terminal whether the current instruction is the right end of the weight limit, if the value is set to true, the node weight is less than the weight of other instructions of the current instruction will not be executed, performs the same weight, is generally used with priority

compile
here to talk about angular instructions compiled three stages

three angular instruction translator stage
1. Standard API conversion browser
will html into dom, so html tags must conform to custom html format
2.angular compile
search directive matches, sorted according to priority, compile and execute the method on a directive
3.angular link
to perform link method on the directive, be scope binding and binding events

the compile
the compile: function (TElement, tAttrs, transclude) {}
the compile function for conversion of the template itself, only the compilation phase run time
function compiler returns directly postllLink, a function representing the link parameters to be executed and to be put back an object contains preLink and postLink

compile:function(tElement,tAttrs,transclude){
//编译阶段...
	return{
		postLink(scope,iElement,iAttrs,controller){
		//编译阶段之后,指令连接到子元素之前
		},
		preLink(scope,iElement,iAttrs,controller){
		//表示在所有子元素都连接之后
		}
	};
}

When defining parameters ignore compile link parameter, because the link function of the instruction to be executed is returned to compile

link
link (scope, iElement, iAttrs, the Controller)
link parameter represents compile returned postLink
prelink representation before after compiling stage instruction is connected to the sub-element running
postLink represent only run after a will are connected in all sub-element command
link function is responsible for correlation between the dynamic model and view, for each instance of each instruction, link function will be executed once

Controller
Controller he would expose a API, using the API may communicate between a plurality of instruction dependency injection

 controller($scope,$element,$attrs,$transclude)

controllerAs
role controllerAs is only from the individual to the controller name, easy to use

The require
The require other instructions can be passed to their
directiveName by naming instructions hump law should specify whether the controller with that instruction, instruction by default from the same elements
^ directiveName Find command in the parent
when the optional? directiveName representing instructions and if not, do not need to throw an exception

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title></title>
</head>
<body>
	<div ng-app='myApp' ng-controller="myCtrl">
		<div book-list></div>
	</div>

</body>
<script src="https://cdn.staticfile.org/angular.js/1.4.6/angular.min.js"></script>
<script type="text/javascript">
	var myApp=angular.module('myApp',[]);

	myApp.directive('bookList',function(){
		return{
			restrict:'ECAM',
			template:'<div><ul><li ng-repeat="book in books">{{book.name}}</li></ul><book-add></book-add></div>',
			replace:true,
			controller:function($scope){
				
				$scope.books=[
					{
						name:'angularjs'
					},
					{
						name:'javascript'
					},
					{
						name:'html'
					}
				];	
				this.addBook=function(){
					$scope.$apply(function(){
						$scope.books.push({name:'css'});
					});
						
					};	

			},
			controllerAs:'bookListController'
		}
	});

	myApp.directive('bookAdd',function(){
		return{
			restrict:'ECAM',
			template:'<button>添加</button>',
			replace:true,
			require:'^bookList',
			link:function(scope,iElement,iAttrs,bookListController){
				iElement.on('click',bookListController.addBook);
			}
		};
	});

	myApp.controller('myCtrl',function($scope){
			//...

	});
</script>
</html>

scope
scope: create a new scope of the current directive, rather than making it inherits the parent scope
scope in three parameters
1.false inherit the parent element scope (default)
2.true create a new scope, but can be inherited from the parent scope
3.object scope independent
object: parameters
&: scope the scope of the parent package as a function of the properties so as to function to read and write the parent scope attributes.
=: scope attributes parent scope attributes two-way binding, modify any party that affect the other side
@: You can only read the value of single parent scope binding
example:

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title></title>
</head>
<body>
	<div ng-app='myApp' ng-controller='firstController'>
		{{books}}

		<!--此books代表父控制器的books,传给了afnc---而afnc传给了a---a在传给了自定义指令的$scope.books-->
		<book-list afnc="books" parent-books='books' parent-title="{{title}}"></book-list>
		
	</div>
</body>
<script src="https://cdn.staticfile.org/angular.js/1.4.6/angular.min.js"></script>
<script type="text/javascript">
	var myApp=angular.module('myApp',[])
	.directive('bookList',function(){
		return{
			restrict:'ECAM',
			template:'<ul><li ng-repeat="book in books">{{book.name}}</li></ul>',
			replace:true,
			controller:function($scope){
				console.log($scope);


				//要用使用函数的方法去使用此属性
				$scope.books=$scope.a();
				//
				//$scope.books=$scope.b
				//
				//$scope.title=$scope.c;
				//console.log($scope.title)


			},

			/*
			*true:创建一个新的作用域,但可以继承父作用域
			false:使用父元素作用域
			对象:也会创建一个有继承链的作用域,默认无法享受继承的作用
			对象参数
			&作用域把副作用域的属性包装成一个函数,从而以函数的方式读写父作用域的属性	()
			=:作用域与父作用域的属性进行双向绑定,及一方修改,另一方会改动
			@:自能读取父元素的值进行单向绑定,只能绑定非引用类型的,不能绑定引用类型的	{{}}
			*/
			//当scope为对象时为一个独立的作用域
			scope:{
				//把父元素的books封装成一个a函数
				a:'&afnc'
				//双向绑定
				//b:'=parentBooks'
				//单向绑定
				//c:'@parentTitle'

			}
		}
	})

	.controller('firstController',function($scope){
			console.log($scope);
			$scope.books=[
				{
						name:'angularjs'
					},
					{
						name:'javascript'
					},
					{
						name:'html'
					}
			];
			$scope.title="标题"
		});
</script>
</html>

Guess you like

Origin blog.csdn.net/qq_44858021/article/details/94758856