简体   繁体   English

无法访问angular.js控制器中的变量

[英]Can't access variable inside angular.js controller

This is my controller: 这是我的控制器:

app.controller("PlaceController", ['$http', function($http){

    this.places = shops;
    var hotels = this;
    hotels.objects = [];
    this.spots = new Array;

    this.newPlace = {};

    this.city = new String();

    this.addPlace = function() {
        this.places.push(this.newPlace);
        this.newPlace = {};

        var request = *some query syntax, sorry for hiding*

        $http.get(request).success(function(data) {
            hotels.objects = data;
            console.log(hotels.objects.elements);
        });

        for (each in hotels.objects.elements) {
          this.spots.push(each.tags.name);
        };

        console.log(this.spots);

}}] );

I get an empty array when I log this.spots to the console. this.spots记录到控制台时,我得到一个空数组。 The http request etc work perfectly because the console.log(hotels.objects.elements) statement works perfectly. http请求等可以完美地工作,因为console.log(hotels.objects.elements)语句可以完美地工作。

Because of this problem, I can't output it into my HTML either. 由于这个问题,我也无法将其输出到HTML中。 What should I do? 我该怎么办?

You are issuing an asynchronous request to get the spots, but you're logging them before they complete. 您正在发出异步请求以获取斑点,但是在它们完成之前对其进行了记录。

Change this.addPlace to log / act on the spots array inside the promise callback: 更改this.addPlace以在promise回调内的spots数组上记录/操作:

this.addPlace = function() {
    this.places.push(this.newPlace);
    this.newPlace = {};

    var request = *some query syntax, sorry for hiding*

    $http.get(request).success(function(data) {
        hotels.objects = data;
        console.log(hotels.objects.elements);

        for (each in hotels.objects.elements) {
          this.spots.push(each.tags.name);
        };

        console.log(this.spots);
    });

You're adding to the spots array before the ajax request is done, move your calls to push inside the callback: 您将在ajax请求完成之前添加到spots数组,移动您的调用以在回调内部进行推送:

$http.get(request).success(function(data) {
        hotels.objects = data;
        console.log(hotels.objects.elements);
        angular.forEach(hotels.objects.elements, function(value) {
                hotels.spots.push(value.tags.name);
        });
});

Also, you should really be using $scope instead of references to this . 另外,您实际上应该使用$scope而不是this的引用。 This would simplify your code a bit, without needing to rename this to hotels 这将简化您的代码位,而无需重新命名thishotels

full controller code using $scope 使用$scope完整控制器代码

app.controller("PlaceController", ['$scope', '$http', function($scope, $http){
    $scope.places = shops;    
    $scope.objects = [];
    $scope.spots = new Array;
    $scope.newPlace = {};
    $scope.city = new String();

    $scope.addPlace = function() {
        $scope.places.push($scope.newPlace);
        $scope.newPlace = {};

        var request = *some query syntax, sorry for hiding*

        $http.get(request).success(function(data) {
            $scope.objects = data;
            console.log($scope.objects.elements);

            angular.forEach($scope.objects.elements, function(value, key) {
                $scope.spots.push(value.tags.name);
            });
            // spots is ready, log it, do whatever
            console.log($scope.spots);
        });       
}}] );

NOTE: Using $scope means you won't need to call this from your html to reference the objects and functions defined in your controller. 注意:使用$scope意味着您不需要从html调用this来引用控制器中定义的对象和函数。

An example: 一个例子:

<div ng-controller="PlaceController">
    <!-- no need to call places.city, if you use $scope just write city -->
    {{city}}
</div>

EDIT : You probably shouldn't use JavaScript's for-in , the problem with it is that it iterates on the names or indexes of your objects/arrays. 编辑 :您可能不应该使用JavaScript的for-in ,它的问题是它会迭代对象/数组的名称或索引

An example: 一个例子:

var someArray = ['a', 'b', 'c'];
for (i in someArray) {
   console.log(i); // prints 0, 1, 2
   console.log(someArray[i]); // prints 'a', 'b', 'c'
}

This is different from any for-in/for-each implementation in other popular languages. 这不同于其他流行语言中的for-in / for-each实现。

Anyway, in this case I've edited the code above to use Angular's forEach , which is a more appropriate solution (many libraries implement custom for-each functions to fix JS's weird for-in ) You can read more in Angular's docs 无论如何,在这种情况下,我已经编辑了上面的代码以使用Angular的forEach ,这是一个更合适的解决方案(许多库实现了自定义的for-each函数来修复JS的怪异for-in ),您可以在Angular的文档中阅读更多内容

Another option, in plain javascript is, if $scope.objects.elements is an array, using the map() function , like this: 纯JavaScript的另一种选择是,如果$scope.objects.elements是一个数组,则使用map()函数 ,如下所示:

$scope.spots = $scope.objects.elements.map(function(value) {
    return value.tags.name; // value is an item in object.elements
});

try this .. 尝试这个 ..

due to your async call you need to perform task inside success 由于您的异步调用,您需要在成功内执行任务

$http.get(request).success(function(data) {
        hotels.objects = data;
        console.log(hotels.objects.elements);

         for (each in hotels.objects.elements) {
              hotels.spots.push(each.tags.name);
          };

        console.log(this.spots);
    });

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

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