AngularJS:如何从父作用域访问子作用域对象?

时间:2013-10-01 22:21:05

标签: angularjs angularjs-scope

function ParentCtrl($ scope){

//某些函数检查子范围内的数据对象是否仍为空

}

function ChildCtrl($ scope){

$scope.data={};
$scope.func = function(){
  $scope.data.x = 1;

}; };

jsFiddle:http://jsfiddle.net/JHwxP/74/

1 个答案:

答案 0 :(得分:0)

您可以使用您可以在此处看到的事件系统:http://jsfiddle.net/patxy/RAVFM/

如果您有2个带共享服务的控制器,您可以这样做:

var myModule = angular.module('myModule', []);
myModule.factory('mySharedService', function($rootScope) {
  var sharedService = {};

  sharedService.message = '';

  sharedService.prepForBroadcast = function(msg) {
    this.message = msg;
    this.broadcastItem();
  };

  sharedService.broadcastItem = function() {
    $rootScope.$broadcast('handleBroadcast');
  };

  return sharedService;
});

function ControllerZero($scope, sharedService) {
  $scope.handleClick = function(msg) {
    sharedService.prepForBroadcast(msg);
  };

  $scope.$on('handleBroadcast', function() {
    $scope.message = sharedService.message;
  });        
}

function ControllerOne($scope, sharedService) {
  $scope.$on('handleBroadcast', function() {
    $scope.message = 'ONE: ' + sharedService.message;
  });        
}

function ControllerTwo($scope, sharedService) {
  $scope.$on('handleBroadcast', function() {
    $scope.message = 'TWO: ' + sharedService.message;
  });
}

ControllerZero.$inject = ['$scope', 'mySharedService'];        

ControllerOne.$inject = ['$scope', 'mySharedService'];

ControllerTwo.$inject = ['$scope', 'mySharedService'];