问题描述
背景:我试图在AngularJS中的指令代码内部发生一些回调。
相关代码:
HTML:
< img-cropper onselect =updateAvatarDatax = 100y =100src ={{tempAvatar}}id =avatarCropper/>
控制器:
$ scope.updateAvatarData = function(c){
alert(Funciona !!!!);
};
指令:
<<这里有更多代码>>
link:function(scope,element,attr){
scope.wsId = attr.id +'WS';
scope.pvId = attr.id +'preview';
scope.x = attr.x;
scope.y = attr.y;
scope.aspectRatio = scope.x / scope.y;
scope.previewStyle =width:+ scope.x +px; height:+ scope.y +px; overflow:hidden;;
scope.onSelectFn = scope。$ eval(attr.onselect);
<<<<更多代码在这里>>
问题出在最后一行scope.onSelectFn = scope。$ eval(attr.onselect) ;。那范围。$ eval(attr.onselect);返回'未定义'。 attr.onselect工作正常,它返回在'onselect'属性中输入的函数的名称。
我使用通过attibutes传递的函数使其他指令无问题,但无法找到我在这里做错了什么。
- 提前致谢
为什么你这样做时,你可以很容易地使用'&'功能与角度
如果你想调用这样的父功能,那么你应该使用$ parse而不是eval看到一个非常低的当使用
link:function(scope,element,attrs){
var parentGet = $ parse(attrs) [ 'ONSELECT']);
var fn = parentGet(scope。$ parent);
fn();
},
Background:I'm trying to run a callback when something inside the code of a directive in AngularJS happen.
Pertinent code:
HTML:
<img-cropper onselect="updateAvatarData" x="100" y="100" src="{{tempAvatar}}" id="avatarCropper"/>
Controller:
$scope.updateAvatarData = function(c){
alert("¡¡¡Funciona!!!!");
};
Directive:
<<more code up here>>
link: function(scope,element, attr) {
scope.wsId = attr.id+'WS';
scope.pvId = attr.id+'preview';
scope.x = attr.x;
scope.y = attr.y;
scope.aspectRatio = scope.x/scope.y;
scope.previewStyle = "width:"+scope.x+"px;height:"+scope.y+"px;overflow:hidden;";
scope.onSelectFn = scope.$eval(attr.onselect);
<<more code down here>>
The problem is in that last line "scope.onSelectFn = scope.$eval(attr.onselect);". That "scope.$eval(attr.onselect);" returns 'undefined'. The attr.onselect works fine, it returns the name of the function typed on the 'onselect' attribute.
I have made others directives with functions passed via attibutes with no problem, but am unable to find what I am doing wrong here.
- Thanks in advance
Why you are doing like this when u can easily use '&' feature available with angular
calling method of parent controller from a directive in AngularJS
Still if you want to call parent function like this then you should be using $parse instead of eval see a very below small example when using
link: function (scope,element,attrs) {
var parentGet = $parse(attrs['onselect']);
var fn = parentGet(scope.$parent);
fn();
},
这篇关于Scope的eval在AngularJS指令中返回undefined的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!