Skip to content

Instantly share code, notes, and snippets.

@shangmin1990
Created April 23, 2014 17:53
Show Gist options
  • Save shangmin1990/11225994 to your computer and use it in GitHub Desktop.
Save shangmin1990/11225994 to your computer and use it in GitHub Desktop.
angular directive compile & link
1.compile:function(elment,attrs){
//....执行scope与dom绑定之前的操作
//ng-repeat为例
//1.clone一个node
var node = element.children().clone();
for(var i=0;i<repeaterCount-1;i++){
element.append(node);
}
//end 到了这一步 所有的node对象都已插入dom元素
//2.link 阶段
return function(scope,element,attrs){
//将特定的scope与特定的元素绑定在一块,确保数据的正确性
}
}
2:关于controller 与 link 的区别
controller中可以实现的功能link中都可以实现的
DEMO://///////////////////////////////////////////////////////////////////////////////
<!DOCTYPE>
<html ng-app="demo">
<head>
<meta chaset="utf-8"/>
<title>ScopeDemo</title>
</head>
<body>
<a href="#/datagrid/a">A</a>
<a href="#/datagrid/b">B</a>
<script id="a.html" type="text/ng-template">
<div>{{id}}</div>
</script>
<div ng-controller="HelloCtrl">
<helloworld hello="{{helloworld}}" clickfn = 'clickfn1();'></helloworld>
</div>
<div ng-view></div>
<script src="angular.js"></script>
<script src="angular-route.js"></script>
<script>
angular.module('demo',['ui','ngRoute']).config(['$routeProvider',function($routeProvider){
$routeProvider.when('/datagrid/:id',{templateUrl:'a.html',controller:'Test'})
.otherwise({"redirectTo":'index.html'});
}]).controller('Test',['$scope','$routeParams',function($scope,$routeParams){
$scope.id = $routeParams.id;
}])
.controller('HelloCtrl',['$scope','$interval',function($scope,$interval){
$scope.clickfn1 =function(){
alert('click');
}
var i = 1;
setInterval(function(){
$scope.$apply(function($scope){
$scope.helloworld = 'zhong'+(i++);
});
},3000);
$scope.helloworld = 'zhong';
$scope.abafdaf = 'fdafda';
}]);
angular.module('ui',[])
.controller('Ctrl',['$scope','$attrs',function($scope,$attrs){
$scope.$watch('hello',function(oldValue,newValue){
console.log($scope.hello.length);
});
$scope.cdef='123'
}])
.directive('helloworld',function(){
return {
restrict:'E',
scope:{
clickfn:'&',
hello:'@'
},
controller:'Ctrl',
templateUrl:'template.html',
link:function(scope,element,attrs){
console.log();
attrs.$observe('hello',function(){
var abc = scope.hello+'='+new Date().toDateString();
scope.hello1 = abc;
});
scope.cdef = '456';
}
}
}).run(function($templateCache){
$templateCache.put('template.html','<div style="height:100px;width:200px;border:1px solid black" ng-click="clickfn()">{{hello}},{{cdef}}</div>')
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment