Share $Scope data between States

2019-03-02 16:37发布

I am trying access the parent state from a child. I tried this but it doesn't work.

angular.module('myApp').controller('compareCtrl', ['$scope',
    function($scope) {
 $scope.test=$scope.$parent.services;

app.coffee

angular
  .module('myApp', ['ngAnimate', 'ngCookies', 'ngResource'
                  , 'ui.router', 'ngSanitize', 'ngTouch'])
  .config ($stateProvider) ->
    $stateProvider.state('home',
      url: "/"
      templateUrl: "home.html"
    ).state('services',
      url: "/services"
      templateUrl: "services/list.html"
    ).state('services.detail',
      url: "/detail/"
      templateUrl: "detail.html"
    ).state('services.compare',
      url: "/compare/"
      templateUrl: "compare.html"
    )

1条回答
太酷不给撩
2楼-- · 2019-03-02 17:19

UI-Router supports data (Model) sharing among state families. The detailed explanation could be found here

How do I share $scope data between states in angularjs ui-router?

Where we can see, that we need to introduce a Model, a cluster, a reference object.

// controller of the parent state 'services'
.controller('ServicesCtrl', ['$scope',
    function($scope) {
        $scope.Model = { prop1 : value1, ...};
}])

Because now each child state will prototypically inherit that reference to $scope.Model... we can access it in any child state controller

.controller('ServiceChildCtrl', ['$scope',
    function($scope) {
        $scope.Model.prop1 = differentValue;
}])

Check it in action in this working plunker

查看更多
登录 后发表回答