Wednesday, 15 July 2015

angularjs - Accessing data from parent controller with child using 'this' -



angularjs - Accessing data from parent controller with child using 'this' -

i found helpful article on stackoverflow:

angularjs access parent scope kid controller

the solution provided access parent's scope, when parent controller global.

so for:

(function() { angular.module.controller('s').controller('parentctrl', function () { var vm = this; vm.cities = ["ny", "amsterdam", "barcelona"]; } }());

(function() { angular.module.controller('s').controller('childctrl', function () { var vm = this; parentctrl.apply(vm, arguments); vm.parentcitiesbyscope = $scope.pc.cities; vm.parentcities = vm.cities; } }());

how can access parentctrl's cities attribute, if place iife each controller? notice parentctrl no longer in same scope kid controller, can't phone call apply function.

if have controllers in separate files, how can access scope of parent?

while having html:

<div ng-app ng-controller="parentctrl pc"> <div ng-controller="childctrl cc"> <pre>{{cc.parentcities | json}}</pre> <pre>{{pc.cities | json}}</pre> </div>

based on modified question, understand want share info across multiple independent controllers. if trying achieve, utilize of these.

use $rootscope share information. since controller scopes inherited $rootscope, can utilize method. however, it's not advisable share methods/functions in $rootscope , should set data. come service hold info in order share information. however, writing service hold info not best practice either. beneficial if outside communication / info modifications implemented within service.

sample service angular.module('myapp') .service('myservice', function() { var cities = ["ny", "amsterdam", "barcelona"]; this.getcities = function() { homecoming cities; } } service usage angular.module('myapp') .controller('mycontroller', function($scope, myservice) { $scope.mycities = myservice.getcities(); }

hope helps.

angularjs

No comments:

Post a Comment