angular.module('myApp',[])
.directive('customTags',function () {
return{
restrict:'ECMA',
template:'<div>{{user.id}}</div>',
replace:true,
compile:function (tElement,tAttrs,transclude) {
//编译阶段
console.log(tElement);
console.log(tAttrs);
console.log(transclude);
//不需要scope,dom渲染前,dom在compile编译阶段改变dom结构
tElement.append(angular.element('<div>{{user.name}}{{user.count}}</div>'));
console.log('customTags compile');
return{
//表示在编译阶段之后,指令直接到子元素之前执行
pre:function preLink(scope,iElement,iAttrs,controller) {
console.log('preLink')
},
//表示在所有子元素指令都连接之后才运行
post:function postLink(scope,iElement,iAttrs,controller) {
iElement.on('click',function () {
scope.$apply(function () {
scope.user.name='ddd';
scope.user.count=++i;
});
});
console.log('postLink');
}
};
//可以直接返回postlink
//return function () {
// console.log('compile return fun');
}
}
})
.directive('customTags2',function () {
return{
restrict:'ECMA',
// template:'<div>aaa</div>',
replace:true,
compile:function (tElement,tAttrs,transclude) {
//编译阶段
console.log('customTags2 compile');
return{
//表示在编译阶段之后,指令直接到子元素之前执行
pre:function preLink() {
console.log('2preLink')
},
//表示在所有子元素指令都连接之后才运行
post:function postLink() {
console.log('2postLink')
}
};
//可以直接返回postlink
//return function () {
// console.log('compile return fun');
// }
}
}
})
.controller('firstController',['$scope',function ($scope) {
$scope.users=[
{
id:10,
name:'张三'
},
{
id:20,
name:'李四'
}
];
}]);