简体   繁体   English

来自AngularJS中另一个类的访问控制器属性

[英]Access controller property from another Class in AngularJS

today I discovered the following problem while using AngularJS. 今天,我在使用AngularJS时发现了以下问题。

My Code is as follows: 我的代码如下:

app.controller("SomeController", function(){

            this.foo = true

            this.changeFoo = function(bool){

                this.foo = bool
            }

            api.check(function(response){
                this.changeFoo(response.bar)
            })
        })

(by the way: response & response.bar are not undefined) (顺便说一句: responseresponse.bar不是未定义的)

api is an instance of my class API , defined outside of my Angular-code. api是我的类API的实例,是在我的Angular代码之外定义的。

The problem is, that I can not change this.foo inside my callback-function. 问题是,我无法在回调函数中更改this.foo

What can I do to access this.foo ? 我该怎么做才能访问this.foo

Edit: 编辑:

I tried to pass this as an argument, the result is the same 我试图将作为参数传递,结果是相同的

api.check(this, function(scope, response){

                scope.foo = response.bar
            })

scope seems to be defined inside this function, but the changes doesn't effect anything 范围似乎是在此函数内定义的,但是更改不会产生任何影响

You need to assign this to a different variable in your angular code before your Api call. 您需要在调用Api之前this值分配给角度代码中的其他变量。 Then use that variable to access your this variable. 然后使用该变量访问this变量。 Like this 像这样

app.controller("SomeController", ['$scope',function($scope){

        this.foo = true;

        this.changeFoo = function(bool){

            this.foo = bool;
            $scope.$apply();
        };
        Var controller=this;

        api.check(function(response){
            controller.changeFoo(response.bar);
        });
    }]);

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

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