简体   繁体   English

如何将值从javascript传递到控制器函数?

[英]How to pass value from javascript to controller function?

I'm completely new into this angular js. 我对这个有角度的js完全陌生。 I have javascript file by using I can able to get some data. 我有javascript文件,可以使用它来获取一些数据。 I want to process that data in controller function. 我想在控制器功能中处理该数据。 But I can't able to do this. 但是我做不到。 I'm already imported controller file also as below, 我已经导入了控制器文件,如下所示

external.js --location /src/js/test.js external.js-位置/src/js/test.js

import MainController from '../../src/app/result/Maincontroller'
....
....
....

var foo = "testdata"

MainController.js MainController.js

Import External from ../../src/js/test.js
angular.module('WebApp').controller('MainCtrl', MainCtrl)
function ResultCtrl ($scope) { 
        $scope.testfunc = function(data) {
        console.log(data)
        }
    }

How to pass this foo value to $scope.testfunc(). 如何将此foo值传递给$ scope.testfunc()。 Please tell me how do I call this controller function from external javascript. 请告诉我如何从外部javascript调用此控制器函数。

You have declared foo as a global variable and should be accessible in your controller by its name (foo). 您已将foo声明为全局变量,并且应该可以在控制器中通过其名称(foo)对其进行访问。 The only thing you need to worry about is that you need to have the reference of the file containing global variable in your view (html file) and that controller's js file is inicluded after the js file containing the variable foo. 您唯一需要担心的是,您需要在视图中引用包含全局变量的文件(html文件),并且在包含变量foo的js文件之后包含控制器的js文件。

Although this will do the job for you but it is not the recommended approach specially in angularjs. 尽管这将为您完成工作,但不是angularjs特别推荐的方法。 You should use Angularjs services for exposing data to controllers. 您应该使用Angularjs服务将数据公开给控制器。

To access a variable foo declared globally, you can use $window.foo . 要访问全局声明的变量foo ,可以使用$window.foo You might need to add the dependency to $window: 您可能需要将依赖项添加到$ window中:

angular.module('WebApp').controller('MainController', ['$window', $window) {
  // Here you can access your global variable as
  console.log('FOO is', $window.foo);
}]);

To call a controller method, you need to bind an action to a DOM element that is managed by your Angular app. 要调用控制器方法,您需要将动作绑定到由Angular应用程序管理的DOM元素。 You should find in your code something like this: 您应该在代码中找到以下内容:

<div ng-app="WebApp" ng-controller="MainController">
  <!-- Everything in here which is ng-something can be managed by Angular -->
  <button ng-click="bar()">This button can call the bar() function</button>
</div>

In the future, start to bind your data with Angular services which are the common best practices to load data in the scope of controllers. 将来,开始将数据与Angular服务绑定,这是在控制器范围内加载数据的常见最佳实践。

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

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