Scope的eval在AngularJS指令中返回undefined [英] Scope's eval returns undefined in an AngularJS directive

查看:128
本文介绍了Scope的eval在AngularJS指令中返回undefined的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景:
我试图在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传递的函数使其他指令无问题,但无法找到我在这里做错了什么。




  • 提前致谢


解决方案

为什么你这样做时,你可以很容易地使用'&'功能与角度



调用方法父控制器从AngularJS中的指令



如果你想调用这样的父功能,那么你应该使用$ 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆