javascript-如何访问具有隔离范围的指令attrs?
作者:互联网
我需要访问指令创建的模型,同时我需要在指令中获取属性.
JS:
module.directive('createControl', function($compile, $timeout){
return {
scope: {
name: '=Name' // Dynamically created ng-model in the directive element
},
link: function(scope, element, attrs){
attrs.$observe('createControl', function(){
attrs.createControl //is empty if scope is an object, otherwise it is passed from html attribute
}
}
HTML:
<div class="control-group" ng-repeat="x in selectedControls">
<div create-control="{{ x }}"></div>
</div>
如果将scope定义为对象,则attrs为空,否则为从html传递的值.
造成这种现象的原因是什么?如何获得对传递的属性和模型的访问?
解决方法:
问题是:create-control需要在父作用域内求值{{x}},但是在声明指令时将作用域设为对象就可以创建隔离作用域.这意味着attrs.createControl无法访问x.因此,它是空的.
一种解决方案:您可以通过几种方法解决此问题,最好的方法是将指令配置为通过属性将scope.createControl接受到其隔离范围中.
工作提琴:http://jsfiddle.net/pvtpenguin/tABt6/
myApp.directive('createControl', function ($compile, $timeout) {
return {
scope: {
name: '@', // Dynamically created ng-model in the directive element
createControl: '@'
},
link: function (scope, element, attrs) {
scope.$watch('createControl', function () {
// the following two statements are equivalent
console.log(attrs.createControl);
console.log(scope.createControl);
})
}
}
})
标签:angularjs,angularjs-directive,angularjs-scope,javascript 来源: https://codeday.me/bug/20191030/1971668.html