角ui.router,从子控制器调用父控制器的功能? [英] Angular ui.router, call parent controller function from child controller?

查看:174
本文介绍了角ui.router,从子控制器调用父控制器的功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的角度与ui.router并建立一个嵌套的视图。父视图有一个div其可见我可以通过父控制器上的功能切换。我想从嵌套视图的子控制器调用此函数。我会怎么做呢?

I'm using Angular with ui.router and have setup a nested view. The parent view has a div whose visibility I can toggle through a function on the parent controller. I'd like to call this function from the child controller of the nested view. How would I do this?

推荐答案

<一个href=\"http://plnkr.co/edit/zw5WJVhr7OKqACoJhDZw?p=$p$pview\">http://plnkr.co/edit/zw5WJVhr7OKqACoJhDZw?p=$p$pview

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>

这是控制器继承中典型,我相信,如果你不重新定义,如果你把它叫做你从父范围相同功能范围的功能,这意味着该范围(这个问题是这样的话使得假设有关上下文的使用这种控制器虽然这是值得商榷的,如果这是真的假设你不依赖于从控制器该控制器一定的影响)的问题。

The scope on controllers is prototypically inherited I believe which means if you don't redefine a function on the scope you get the same function from the parent scope if you call it (the problem is this then makes the assumption about the context of the use of this controller though it's debatable if this is really an issue assuming you don't depend on some effect from that controller in this controller).

这篇关于角ui.router,从子控制器调用父控制器的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆