0

today I discovered the following problem while using 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)

api is an instance of my class API, defined outside of my Angular-code.

The problem is, that I can not change this.foo inside my callback-function.

What can I do to access 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

4
  • 1
    api.check.call(this, function() { .., or just use the classic var self = this Commented Dec 12, 2015 at 18:21
  • I dont know why, but this does not work. Commented Dec 12, 2015 at 18:33
  • jsfiddle.net/mu4kfbjt Commented Dec 12, 2015 at 18:40
  • var vm = this; so you are a reference to use in api block Commented Dec 12, 2015 at 19:33

1 Answer 1

1

You need to assign this to a different variable in your angular code before your Api call. Then use that variable to access your this variable. 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);
        });
    }]);
Sign up to request clarification or add additional context in comments.

2 Comments

as you can see there are no errors. can you give me a working example?
its running you just need to use $scope.apply() to update the document

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.