嗨,哪个更好?有什么关系?优点和缺点是什么?
以下是两者的比较代码:
作用域:{ 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>要求:'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>PS请注意,这两种代码都是相同的。用模型的值在控制台上记录
发布于 2016-06-03 12:55:20
与scope:{ngModel:'='},
它创建一个带有隔离作用域的指令,这里的作用域基本上是孤立的,它不继承父$scope,但是值被传递到该指令所需的指令中。如果您使用'=‘,那么它是双向数据绑定。
好的优点和缺点取决于你的需求。
优势:
$scope.$watch来更新指令中的视图。做这项工作。reusable component,可以在应用程序中的多个位置使用。directive controller中直接使用传递给隔离作用域的作用域变量。disadvantages:
用require:'ngModel'
优势:
publish-subscribe design pattern)工作良好。disadvantage
link function以便获得父控制器及其作用域、变量和方法。$scope.$watch更新视图。this和$scope时,指令控制器或链接都会受到干扰。https://stackoverflow.com/questions/37613598
复制相似问题