user5852854 user5852854 - 1 month ago 16
AngularJS Question

Components, binding in Angularjs1.5 - Passing data from one controller to another

After I get the accounts and people array from my resolve, how do I access people and accounts in the component controller? I have also tried the define acctTally in the main ctl and and bind it to the component with no luck.

I can bind people and account just find to the component and access it in the component template, but it I want to do work on either array in the component controller is where I'm having the issue. What key concept am I missing????


main controller


angular.module('hellosolarsystem')
.controller('AcctCtrl', function($scope, accounts, people){
$scope.accounts = accounts;
$scope.people = people;
});



Main template


<nav-bar></nav-bar>
<acct-list people="people" accounts="accounts"></acct-list>



Component


function aCtrl(){
var ctrl = this;
ctrl.acctTally = [];
ctrl.uniqueAcct = [];

//Array of all accounts
$scope.people.data.forEach(function(person){
person.account_types.forEach(function(account){
ctrl.acctTally.push(account.name);
})
});
}
angular.module('hellosolarsystem').component('acctList', {
bindings: { accounts: '<',
people: '<'
},
controller: aCtrl,


templateUrl: 'javascripts/app/components/accounts/acctsList/index.html'
})



Component Template


<table class = "table">
<thead>
<tr>
<th>Accounts</th>
<th>Number of Accounts Assigned Users</th>
</tr>
</thead>
<tbody>
<tr ng-repeat = "acct in $ctrl.acctTally">
<td>{{acct.name}}</td>
<td>{acct.tally}}<</td>
<td>
<button class = "btn btn-info" ng-click = "editUser($index)">Edit</button>
<button class = "btn btn-danger" ng-click = "deleteUser($index)">Delete</button>
</td>
</tr>
</tbody>
</table>

Answer Source

Binding for component doesn't available when you controller function gets instantiated since AngularJS 1.6 release. Check breaking changes here. Bindings will be available when $onInit hook gets called unlike Angular 2+. Even you could enforce the older behaviour of prepopulate bindings when controller gets instantiated by doing

.config(function($compileProvider) {
    $compileProvider.preAssignBindingsEnabled(true);
})

But doing above is highly discourage by Angular team.

Per 1.6.0 breaking changes you have to move your code to $onInit hook solve your issue.

ctrl.$onInit = function() {
 ctrl.people.data.forEach(function(person){
    person.account_types.forEach(function(account){
       ctrl.acctTally.push(account.name);
    })
 });
}