Dea*_*ada 5 javascript angularjs
嗨哪个更好?有什么不同?优缺点都有什么?
以下是两者之间的比较代码:
范围:{ngModel:'='}
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="app">
<input ng-model="code"></my-directive>
</div>
<script type="text/javascript">
app = angular.module('app', []);
app.directive('input', function(){
return {
scope: {
ngModel: '='
},
link: function(scope, element, attrs){
scope.$watch('ngModel', function(value){
console.log(value);
})
}
}
});
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
require:'ngModel',
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="app">
<input ng-model="code"></my-directive>
</div>
<script type="text/javascript">
app = angular.module('app', []);
app.directive('input', function(){
return {
require: 'ngModel',
link: function(scope, element, attrs, ngModel){
attrs.$observe('ngModel', function(value){
scope.$watch(value, function(newValue){
console.log(newValue);
});
});
}
}
});
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
PS请注意,两个代码都是一样的.使用模型的值登录控制台
与范围:{ngModel: '='} ,
它创建了一个带隔离范围的指令,这里基本上是作用域被隔离并且它不从父$ scope继承,但是值被传递到该指令所需的指令中.如果你使用'='那么它的双向数据绑定.
优点和缺点取决于您的要求.
好处 :
$scope.$watch
如果父作用域变量的值发生更改,则无需每次都使用,以便更新指令中的视图.'='完成这项工作.reusable component
,可以在您的应用程序中的多个位置使用.directive controller
即使指令中不存在链接函数,也可以直接在您的文件中使用传递给隔离范围的范围变量.缺点:
with require:'ngModel'
好处:
publish-subscribe design pattern
).坏处
link function
顺序获取父控制器及其范围变量和方法.$scope.$watch
如果父项范围变量发生变化,则需要使用更新视图. this
和$scope
归档时间: |
|
查看次数: |
5289 次 |
最近记录: |