默认是共享作用域:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body ng-app="myApp" ng-controller="mainController">
<ceshi></ceshi>
<script src="angular.js"></script>
<script>
var myApp = angular.module('myApp',[]);
myApp.directive('ceshi',function(){
var option = {
template:'<p>{{abc}}</p>'
};
return option;
});
myApp.controller('mainController',function($scope){
$scope.abc = 'ericzheng';
});
</script>
</body>
</html>
当我们自己创建某个指令时,这个指令肯定不可能只使用一次,是要重复多次使用的,有的在一个页面内或者一个控制器内需要使用多次。
类似上面的这种场景,在任何一个输入框内改变数据,都会导致其他的标签内的数据一同发生改变,这显然不是我们想要的,这个时候就需要独立作用域了。
想转换成独立作用域只需要一行代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body ng-app="myApp" ng-controller="mainController">
<ceshi></ceshi>
<script src="angular.js"></script>
<script>
var myApp = angular.module('myApp',[]);
myApp.directive('ceshi',function(){
var option = {
template:'<p>{{abc}}</p>',
scope:{}
};
return option;
});
myApp.controller('mainController',function($scope){
$scope.abc = 'ericzheng';
});
</script>
</body>
</html>
单向数据绑定:
@操作符,双引号内的内容当作字符串进行绑定
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body ng-app="myApp" ng-controller="mainController">
<my-directive name="aaaa"></my-directive>
<script src="angular.js"></script>
<script>
var myApp = angular.module('myApp',[]);
myApp.directive('myDirective',function(){
var option = {
template:'<p>wew{{name}}<p/>',
scope:{
name:'@'
}
};
return option;
});
myApp.controller('mainController',function($scope){
});
</script>
</body>
</html>
单向绑定,从当前指令的属性中获取到值,然后赋值给当前独立作用域里的这个属性
双向数据绑定
=操作符 绑定的是个变量
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body ng-app="myApp" ng-controller="mainController">
<input type="text" ng-model="abc">
<my-directive name="abc"></my-directive>
<script src="angular.js"></script>
<script>
var myApp = angular.module('myApp',[]);
myApp.directive('myDirective',function(){
var option = {
template:'<p>wew{{name}}<input ng-model="name"><p/>',
scope:{
name:'='
}
};
return option;
});
myApp.controller('mainController',function($scope){
$scope.abc = 'ericzheng';
});
</script>
</body>
</html>
name="abc"这个是核心,左边联结的是独立作用域,右边联结的是外部的作用域里的模型abc
使用父作用域的行为
&操作符 绑定的内容是个方法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body ng-app="myApp" ng-controller="mainController">
<my-directive fn1="fn2(name)"></my-directive>
<script src="angular.js"></script>
<script>
var myApp = angular.module('myApp',[]);
myApp.directive('myDirective',function(){
var option = {
restrict:'E',
template:'<button ng-click="fn1({name:\'username\'})">wfewef</button>',
scope:{
fn1:'&'
}
};
return option;
});
myApp.controller('mainController',function($scope){
$scope.fn2 = function(attr){
console.log(attr);
}
});
</script>
</body>
</html>
如何看懂:
先不管指令内部是怎么实现的,先看怎么用的,然后看一下对应的父作用域里的变量或方法是怎么定义的。