sadrzadehsina sadrzadehsina - 2 months ago 10
Ajax Question

pass parameter to angular component after ajax request

I am dealing with angular 1 component, I made a datatable component which accepts a dataset as a parameter.

here is how I am using

datatable
component.

index.html


...
<datatable dataset="ViewModel.dataset"></datatable>
...


index.controller.js


(function() {

'use strict';

angular
.module('DashboardApplication')
.controller('PagesIndexController', PagesIndexController);

function PagesIndexController() {

var self = this;

self.dataset = {};

Restangular.one('someurl').get().then(function( pages ) {
self.dataset = pages;
});
}
})();


datatable.component.js


(function() {

'use strict';

angular
.module('DashboardApplication')
.component('datatable', {
bindings: {
dataset: '<'
},
templateUrl: '/frontend/templates/dashboard/components/data-table.html',
controller: 'DataTableController'
});

})();


datatable.controller.js


(function() {

'use strict';

angular
.module('DashboardApplication')
.controller('DataTableController', DataTableController);

function DataTableController() {
var self = this;
console.log(self.dataset); // which is undefined!
}

})();


The problem is I'm getting
undefined
for
dataset
in
datatable.controller.js
. Is there any solution for this?!

Answer

Use the $onChanges life-cycle hook to see the value when it becomes defined:

  angular
    .module('DashboardApplication')
    .controller('DataTableController', DataTableController);

  function DataTableController() {
    var self = this;
    //console.log(self.dataset); // which is undefined!
    this.$onChanges = function(changesObj) {
        if (changesObj.dataset) {
            console.log(changesObj.dataset.currentValue);
        };
    });
  }

For more information, see AngularJS Developer Guide -- Components.

Comments