2016-09-18 122 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