我需要访问指令创建的模型,同时我需要在指令中获取属性。
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>
If scope
被定义为一个对象,attrs
为空,否则为从html传递的值。
这种行为的原因是什么?如何访问传递的属性和模型?
问题: create-control
需要评估{{x}}
在父范围内,但是通过使scope
声明指令时的对象将创建一个隔离范围。这意味着attrs.createControl
无权访问x
。因此,它是空的。
一种解决方案:您可以通过多种方式解决此问题,其中最好的方法是将您的指令配置为接受scope.createControl
通过属性进入其隔离范围。
工作小提琴: http://jsfiddle.net/pvtpenguin/tABt6/ 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);
})
}
}
})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)