2016-09-18 125 views
0

我正在处理角度1组件,我制作了一个接受数据集作为参数的数据表组件。这个是我如何使用datatable组件。在ajax请求后将参数传递给角度组件

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! 
    } 

})(); 

问题是我得到undefineddatasetdatatable.controller.js。有没有解决方案?

回答

2

使用$onChanges生命周期挂钩看到的价值,当它变成定义:

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); 
     }; 
    }); 
    } 

欲了解更多信息,请参阅AngularJS Developer Guide -- Components

1

我认为你缺少从你的分量

controllerAs: 'vm' 

线,将模型绑定到“本”的控制器,而不是$范围(也意味着你可以达到你的视图模型为“VM”您的看法,像里面:

ng-if="vm.dataset" 

但我认为它仍然在确切的时间是不确定的,你有几种选择在这里:

  1. 你可以将承诺传递给组件,然后写一个然后
  2. 你可以放置一个ng-if =“数据集& &数据集长度”,你可以在外部html中调用组件。这样,组件内的逻辑只有在属性中有实际数据时才会触发。

    <datatable ng-if="ViewModel.dataset" dataset="ViewModel.dataset"></datatable> 
    
  3. ,你也可以写这样的事情在你的组件:

    $scope.$watch('self.dataset', function() { 
        if (self.dataset) { 
         alert ('hi'); 
        } 
    }); 
    
+1

我使用'component',它不需要'controllerAs'。它默认使用'$ ctrl'作为'controllerAs'。 – sadrzadehsina