2013-10-01 147 views
0

功能ParentCtrl($範圍){AngularJS:如何從父範圍訪問子範圍對象?

//一些功能檢查兒童範圍的數據對象是否仍是空

}

功能ChildCtrl($範圍){

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

}; };

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

+0

您不能從父範圍訪問子範圍.http://stackoverflow.com/questions/13428042/angularjs-access-to-child-scope – geniuscarrier

+0

定義父範圍的屬性和 從子範圍訪問它ES。範圍繼承原型。 看到這個:http://jsfiddle.net/yjVD9/1/ 非常有幫助! – 9blue

回答

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'];