2

我是 AngularJS 的新手,我正在为我的 SPA 使用 Angular UI-Router。

我要做的是从子视图更新父视图值。我已经浏览了嵌套视图和多视图的 UI-Router 文档,但找不到更新值的方法。

我的用例是,父视图将是标题,每次子视图通过状态转换更改时,我都想更新作为父视图一部分的标题值。

代码 :

HTML 文件 -

<div ui-view></div>

发生 Angular UI-Routing 配置的 JS 文件 -

angular.module('myApp', ['ui.router']).config(['$stateProvider', '$routeProvider',
function($stateProvider, $routeProvider) {
  $stateProvider
    .state('main', {
      resolve: {
        resA: function() {
          return {
            'value': 'Hello !!'
          };
        }
      },
      controller: function($scope, resA) {
        $scope.resA = resA.value;
      },
      abstract: true,
      url: '/main',
      template: '<h1>{{resA}}</h1>' +
        '<div ui-view></div>'
    })
    .state('main.one', {
      url: '/one',
      views: {
        '@main': {
          template: "Im View One"
        }
      },
      resolve: {
        resB: function(resA) {
          return {
            'value': resA.value + ' from One'
          };
        }
      },
      controller: function($scope, resA, resB) {
        $scope.resA = resB.value;
      }
    }).state('main.two', {
      url: '/two',
      views: {
        '@main': {
          template: '<div ui-view="sub1"></div>' +
            '<div ui-view="sub2"></div>'
        },
        'sub1@main.two': {
          template: "Am awesome"
        },
        'sub2@main.two': {
          template: "Am awesome two/too"
        }
      },
      resolve: {
        resC: function(resA) {
          return {
            'value': resA.value + ' from Two'
          };
        }
      },
      controller: function($scope, resA, resC) {
        $scope.resA = resC.value;
      }
    });
}]).run(['$rootScope', '$state', '$stateParams', function($rootScope, $state, $stateParams) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
$state.transitionTo('main.two');
}]);

这是同一代码段的JSFiddle 链接。

4

1 回答 1

4

有多种方法可以更新父范围。

  1. 使用控制器 作为 https://jsfiddle.net/9n7wrevt/17/

      controller: function($scope, resA) {
        this.resA = resA.value;
      },
      controllerAs: 'main'
    

    参考父母如下

    控制器:函数($scope,resB){ $scope.main.resA = resB.value; }

  2. 使用 $parent https://jsfiddle.net/9n7wrevt/18/

    控制器:函数($scope,resB){ $scope.$parent.resA = resB.value; }

  3. 更好的方法(强烈推荐)是使用 $scope $emit, $on 在控制器之间进行通信。 https://jsfiddle.net/9n7wrevt/19/

于 2016-05-28T08:13:34.807 回答