我将 Angular 与 ui.router 一起使用,并设置了嵌套视图。父视图有一个 div,我可以通过父控制器上的函数切换其可见性。我想从嵌套视图的子控制器调用此函数。我该怎么做?
http://plnkr.co/edit/zw5WJVhr7OKqACoJhDZw?p=preview http://plnkr.co/edit/zw5WJVhr7OKqACoJhDZw?p=preview
JS
angular
.module("myApp", [])
.controller("parent", function($scope) {
$scope.parentFunction = function() {
alert("Called a function on the parent")
};
})
.controller("child", function($scope) {
$scope.childFunction = function() {
alert("Called a function on the child")
};
$scope.parentFromChild = function() {
alert("I know this feels weird");
$scope.parentFunction();
};
})
HTML
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js@*" data-semver="1.2.14" src="http://code.angularjs.org/1.2.14/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="parent">
<div ng-controller="child">
<a href="#" ng-click="parentFunction()">Call Parent</a>
<a href="#" ng-click="childFunction()">Call Child</a>
<a href="#" ng-click="parentFromChild()">Call Parent from Child</a>
</div>
</div>
</body>
</html>
我相信控制器上的作用域是原型继承的,这意味着如果您不在作用域上重新定义函数,那么如果您调用它,您会从父作用域中获得相同的函数(问题是这会做出有关使用上下文的假设尽管假设您不依赖于该控制器中该控制器的某些效果,但这是否确实是一个问题是有争议的)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)