详解详解angularjs中的隔离作用域理解以及绑定策略中的隔离作用域理解以及绑定策略
我们首先看下面的例子:
<!doctype html>
<html ng-app="MyModule">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="css/bootstrap-3.0.0/css/bootstrap.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external
nofollow" >
</head>
<body>
<hello></hello>
<hello></hello>
<hello></hello>
<hello></hello>
</body>
<script src="framework/angular-1.3.0.14/angular.js"></script>
<script src="IsolateScope.js"></script>
</html>
我们在看看IsolateScope中的代码:
var myModule = angular.module("MyModule", []);
myModule.directive("hello", function() {
return {
restrict: 'AE',
template: '<div><input type="text" ng-model="userName"/>{{userName}}</div>',
replace: true
}
});
这时候当运行页面的时候发现只要有一个input中的输入变化了,这时候所有的nput的内容都会变化:
这样就会面临一个问题:我们的指令无法单独使用,于是就有了独立作用域的概念。
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
}
});
通过把scope设置为{},那么每一个指令就具有自己独立的scope空间,于是就不会相互影响了。但是angularjs中最重要的概
念是:绑定策略。其具有绑定策略如下:
第一步:第一步:我们看看原始的方式,也就是不使用上面的三种绑定方式