如何从其父范围调用在子范围中定义的方法?
function ParentCntl() { // I want to call the $scope.get here } function ChildCntl($scope) { $scope.get = function() { return "LOL"; } }
http://jsfiddle.net/wUPdW/
您可以$broadcast从父母到孩子使用:
$broadcast
function ParentCntl($scope) { $scope.msg = ""; $scope.get = function(){ $scope.$broadcast ('someEvent'); return $scope.msg; } } function ChildCntl($scope) { $scope.$on('someEvent', function(e) { $scope.$parent.msg = $scope.get(); }); $scope.get = function(){ return "LOL"; } }
工作jsfiddle:http : //jsfiddle.net/wUPdW/2/
更新 :还有另一个版本,耦合性更低,更易于测试:
function ParentCntl($scope) { $scope.msg = ""; $scope.get = function(){ $scope.$broadcast ('someEvent'); return $scope.msg; } $scope.$on('pingBack', function(e,data) { $scope.msg = data; }); } function ChildCntl($scope) { $scope.$on('someEvent', function(e) { $scope.$emit("pingBack", $scope.get()); }); $scope.get = function(){ return "LOL"; } }
jsfiddle:http : //jsfiddle.net/uypo360u/