Это меняет контекст, и это неопределенный angularjs

#angularjs #scope #this

#angularjs #область действия #это

Вопрос:

У меня есть функция, подобная приведенной ниже, и у меня проблема из-за this контекста. Когда я запускаю свой код, у меня в консоли появляется ошибка: Cannot set property 'cat' of undefined когда я меняю this.cat на $scope.cat , все в порядке. Я попытался добавить $ scope.apply и тайм-аут, но это не работает. Похоже, это меняет контекст, но я не знаю, как это исправить.

 (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 amp;amp; testValue.data) {
              this.cat = testValue.data
            }
          })
       }
    })
  })()
  

Ответ №1:

Проблема в том, что вы используете ArrowFunction в качестве контроллера, так что this в этом случае была бы функция IFFE, которая оборачивает весь код.

Вам нужно будет изменить функцию ArrowFunction на обычную, что создаст для нее отдельный this контекст.

 (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 amp;amp; testValue.data) {
            this.cat = testValue.data
          }
        })
      }
    })
})()