0

I have function like below, and I have problem because of this context. When I run my code, I have error in my console: Cannot set property 'cat' of undefined When I change this.cat for $scope.cat, everything is fine. I tried add $scope.apply and timeout, but it doesn't works. It seems like this change context, but I dont't know how to repair it.

(function () {
    angular.module('test.module')
      .component('testComponent', {
        bindings: {},
        templateUrl: 'js/modules/test/test.html',
        controllerAs: 'vm',
        controller: (TestService, $scope) => {  

          TestService.changed(() => {
            const testValue = test.findById(id)

            if (testValue && testValue.data) {
              this.cat = testValue.data
            }
          })
       }
    })
  })()

1 Answer 1

1

The problem is that you are using arrowFunction as the controller, so, the this in that case would be the IFFE function that wraps the entire code.

You will need to change the arrowFunction to regular one, that will create a separate this context for it.

(function() {
  angular.module('test.module')
    .component('testComponent', {
      bindings: {},
      templateUrl: 'js/modules/test/test.html',
      controllerAs: 'vm',
      controller: function(TestService, $scope) {

        TestService.changed(() => {
          const testValue = test.findById(id)

          if (testValue && testValue.data) {
            this.cat = testValue.data
          }
        })
      }
    })
})()
Sign up to request clarification or add additional context in comments.

Comments

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.