简体   繁体   English

将对象传递给指令不允许全局变量

[英]Passing object to directive does not allow global variables

Im passing to my directive a variable col defined col: '=' in the directive. 我将指令col定义为col: '='的变量col传递给指令col: '=' The object contains some arrays, and inside those arrays there is a function. 该对象包含一些数组,并且在这些数组中有一个函数。 The function refers to a variable from my controller, and it looks like this: 该函数从我的控制器引用了一个变量,它看起来像这样:

function (params) {
    return $scope.function(params);
}

This col variable is being passed to a sub directive that the big directive contains, and the sub-directive executes it. col变量将传递给big指令包含的子指令,然后该子指令将其执行。

It throws an error, from a file called VM{random number here} where it says that $scope is undefined. 它从一个名为VM {random number here}的文件抛出错误,该文件说$scope未定义。

How can I make it run from my controller, and not from a virtual JS file? 如何使其从我的控制器而不是虚拟JS文件运行?

if you need to pass functionality then you must create service/factory for the job.To use in directive or component i think. 如果您需要通过功能,则必须为该作业创建服务/工厂。我认为要在指令或组件中使用。

Dont forget services are singleton and factory implements standart factory pattern. 不要忘记服务是单例的,工厂实施标准的工厂模式。

If global means window variables or function dont need to injection just this.windows. 如果全局意味着窗口变量或函数不需要仅注入this.windows。 .... does the job. ....做这份工作。

regards. 问候。

call your directive in your html template which you declared for your controller 在为控制器声明的html模板中调用您的指令
and simply pass data from your directive to the function used in your controller 并将数据从指令直接传递给控制器​​中使用的函数
so that you can access your directive data on same rendering template of your controller 这样您就可以在控制器的同一渲染模板上访问指令数据

Directive 指示

.directive('myDir', function () {
   return {
     'restrict': 'AE',
     'templateUrl': '/directive_page.html',
         'scope': {
           'col': '=',
           'onSelect': '='
         }
   }
   'link': function () {
       // use onselect method here to use values
   }
}

Controller 控制者

.controller('myController', function () {
    $scope.setValueFromDirective = function (value) {
       // write your logic to fetch data
    };
});

HTML 的HTML

<div data-my-dir="" col="//pass value you want in directive" data-on-select='setValueFromDirective(value)'>
</div>

I hope this will help you 我希望这能帮到您

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM