微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

angularjs – Angular ui.router,从子控制器调用父控制器函数?

我使用Angular与ui.router并设置了嵌套视图.父视图有一个div,其可见性可以通过父控制器上的函数切换.我想从嵌套视图的子控制器调用函数.我该怎么做?
http://plnkr.co/edit/zw5WJVhr7OKqACoJhDZw?p=preview

JS

// Code goes here

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>

控制器上的范围是原型继承的,我相信这意味着如果您不重新定义范围上的函数,从父范围获得相同的函数(如果您调用它)(问题是这样做就假定使用的上下文的控制器,虽然这是有争议的,如果这真的是一个问题,假设你不依赖于该控制器中的某些效果).

原文地址:https://www.jb51.cc/angularjs/140811.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐