如何将Angular变量注入JavaScript变量

How to inject an Angular variable into a JavaScript variable?

本文关键字:变量 注入 JavaScript Angular      更新时间:2023-09-26

我的角度控制器中有这个功能:

$scope.get_all_places = function () {
    $http.get("get-all-places").then(function (response) {
        $scope.selected_place = eval(response.data[0]);
    });
};

我想把我从$scope.selected_place得到的值设置为这个JavaScript代码:

var $shape_options = selected_place.shape_attributes;
var $map_options = selected_place.map_attributes;
switch ($shape_options.shape_type) {
    case 'circle':
        var $center = selected_place.center;
        var $radius = selected_place.radius;
        break;
    case 'rectangle':
        var $bounds = selected_place.rectangle;
        break;
    case 'polygon':
        var $path = selected_place.polygon;
        break;
}

但是angular之前执行的JavaScript代码从服务器获取数据的问题。

有什么办法吗?

将所有代码放在ajax调用的then函数中,ajax异步执行

$scope.get_all_places = function () {
    $http.get("get-all-places").then(function (response) {
        $scope.selected_place = eval(response.data[0]);
        var $shape_options = selected_place.shape_attributes;
var $map_options = selected_place.map_attributes;
switch ($shape_options.shape_type) {
    case 'circle':
        var $center = selected_place.center;
        var $radius = selected_place.radius;
        break;
    case 'rectangle':
        var $bounds = selected_place.rectangle;
        break;
    case 'polygon':
        var $path = selected_place.polygon;
        break;
    });
 other_functions($map_options);//call the functions that need the $map_options variable
};

您可以创建一个函数:

function determineShape(selected_plane){
    var $shape_options = selected_place.shape_attributes;
    var $map_options = selected_place.map_attributes;
    switch ($shape_options.shape_type) {
        case 'circle':
            var $center = selected_place.center;
            var $radius = selected_place.radius;
            break;
        case 'rectangle':
            var $bounds = selected_place.rectangle;
            break;
        case 'polygon':
            var $path = selected_place.polygon;
            break;
    }
}

然后在承诺响应中调用它:

$scope.get_all_places = function () {
    $http.get("get-all-places").then(function (response) {
        // Run after promise is returned
        determineShape(response.data[0]);
    });
};

在jQuery:中获取变量

试试这个

var selected_place = $('[ng-controller="your controller name here"]').scope().selected_place;

小错误:

再试一次:

var selected_place = $('[ng-controller="your controller name here"]').scope().get_all_places;

不是最整洁的解决方案,但您可以将值放入hidden输入字段,然后将其设置为JS变量,类似于:

<input id="selected_place" type="hidden" value="{{ selected_place }}"/>

和JS

document.getElementById("selected_place").value;