fiddle: http://jsfiddle.net/6rbj5/1/
so want access object parent scope modified in child scope.
function parent($scope) { $scope.data = null; } function child($scope) { $scope.data = [{id:1}, {id:2}] }
html:
<div ng-controller="parent"> data length: {{ data.length }}<br> <div ng-controller="child"></div> </div>
however length prints nothing. ideas how fix this?
$scope.$parent.data = [{id:1}, {id:2}]
although doesn't feel right.
another create empty array in parent, , modify instead of replacing in child.
or maybe need use service; depends on trying accomplish.
defining service:
var myapp = angular.module('myapp', []); myapp.factory('tickets', function factory() { var tickets = []; function add(ticket){ tickets.push(ticket); } function count(){ return tickets.length; } return { add: add, count: count }; });
using service:
function parent($scope, tickets) { $scope.tickets = tickets; } function child($scope, tickets) { tickets.add({id:1}); tickets.add({id:2}); }
html:
<div ng-controller="parent"> data length: {{ tickets.count() }}<br> <div ng-controller="child"> </div> </div>
notice how clean , business-modelly controllers are, , can extend tickets concept cleanly in 1 place , access anywhere injecting controller. can without worrying hierarchy or relationship between controllers or polluting environment. on other hand might overkill if application extremely simple.
Comments
Post a Comment