如何将数组值从 javascript 传递到 angularjs 控制器

How to pass array values from javascript to angularjs controller

我正在尝试传递我从 JavaScript 文件的数组中获取的值,并使用全局变量

将其推送到 angularJS

在 angular 文件中,我试图通过访问全局变量来获取这些值,例如 但它 returns 我未定义 但是我 运行

如何在我的控件中访问这些值

全局变量不是一个好主意,也许你需要与另一个网站或框架进行交互。

是否应该使用全局变量,可以在index.html

中用特殊脚本声明
<script type="text/javascript">    
 let globalarray; 
</script>

您也可以将全局数组分配给 属性 of window

window.globalarray

或$rootScope.

以你上面的例子为例。

  1. 您没有推送 globalarray 中的值。通过不调用 abc() 函数。

  2. 如果您的 globalarray 变量是 window 全局级别,那么它可以在您的 angular 应用程序的任何地方使用。

请观察我为演示而制作的 fiddle 中的行为。我也做了一个plunk让你看清楚。

Fiddle

var globVar = [12 ,33];
var myApp = angular.module('myApp', []);    
myApp.controller('MyController', function($scope) {      
  $scope.globVar = globVar;
}); 

更新

由于数据来自回调,您需要重新 运行 摘要循环并更新变量。请注意这个 fiddle 因为它有你的坐标 init.

// we got the cords
var cords = ol.proj.transform(coordinates, 'EPSG:3857', 'EPSG:4326');

// we get the scope from the element that has the controller binded to it.
var scope = angular.element(document.getElementById("MainWrap")).scope();

// we call a digest cycle of angular to update our scope variable sinse it comes in a callback when angular is loaded
scope.$apply(function () {
   scope.updateCords(cords);
});

Working Fiddle

希望对您有所帮助。

试试这个:

$scope.globalarray = [];

function abc() {
   var array = [4,5]
   angular.forEach(array,function(k,v){
     $scope.globalarray.push(k); 
  })

}

看看这个link:

AngularJS access scope from outside js function

你可以用不同的方式来思考它,一旦你可以访问范围,你只需使用数组中的数据调用控制器内的 setter 方法,然后你就可以做任何你需要的事情.我在一个项目中使用过这种方法,效果很好。

示例:

//externalScope是在angular控制器中声明的全局变量 //这是一种从angular外部访问控制器和触发器方法的方法 //我们想要的只是向 angular 发出信号,表明某些数据已更改,因此它可以做一些事情。在我的示例中,selectedUserValue 是我传递给控制器​​的数据位。

if (externalScope) {
    externalScope.$apply(function () {
        externalScope.selectUser(selectedUserValue);
    });
}

无论您何时尝试使用一些数据调用范围方法,此代码都存在于控制器之外

现在在实际控制器中我们有这样的东西:

    var externalScope;

    (function () {
   controller code

控制器中的某处:

externalScope = $scope; //this exposes the scope to the outside world

注意 externalScope 变量是如何在控制器外部声明的,因此它将是全局变量。

在此之后,只需在从外部调用的 angular 方法中编写您需要的任何代码即可。

在我的例子中,它是一个 setter,然后它调用其他使用该数据的东西:

$scope.selectUser = function (userID) {
            if (userID && userID !== $scope.selectedUserID) {
                $scope.selectedUserID = userID;
                $scope.loadUserRecords();
            }
        };

希望这是有道理的。免责声明...这不是我所说的微不足道的东西,只有在您真的别无选择时才应使用!