Rawle Juglal
Rawle Juglal

Reputation: 405

AngularJS component bindings not passing object

Receiving error cannot read property 'type' of undefined at PollListCtrl.runQuery. I'm not sure why this is coming up undefined. I've console logged profile-polls.controller.js where listConfig is created to make sure there is an object here. The response is

{type: "all", filters: {pollsCreated: Array(3)}}

But it is coming up undefined when I try to pass it to poll-list component in the profile-polls.html. Below is the gist for the relevant files. Can anyone tell me why this is not passing correctly?

https://gist.github.com/RawleJuglal/fa668a60e88b6f7a95b456858cf20597

Upvotes: 2

Views: 965

Answers (2)

Maxim Shoustin
Maxim Shoustin

Reputation: 77904

I think you need to define watcher for your component. On start listConfig is undefined and only after some delay (next digest cycle) it gets value. So we create watcher and cancel it after if statement.

app.component('pollList', {
  bindings: {
    listConfig: '='
  },
  templateUrl: 'poll-list.html',
  controllerAs: 'vm',
  controller: PollListCtrl
});

function PollListCtrl($scope) {

    var vm = this;

    function run(){
      console.log(vm.listConfig);
    }


    var cancelWatch = $scope.$watch(function () {
        return vm.listConfig;
    },
    function (newVal, oldVal) {

        if (newVal !== undefined){
            run();
            cancelWatch();
        }
    });
}

Demo plunkr

Upvotes: 1

Ravi Kumar
Ravi Kumar

Reputation: 68

  • You should never use $scope in your angularjs application.
  • You can use ngOnInit() life cycle hook to access "bindings" value instead constructor.

    ngOnInit(){

    $ctrl.listConfig = { type: 'all' };

    $ctrl.limit = 5;

    }

Upvotes: 0

Related Questions