angular 子元素访问父元素的$scope

若html如下:

<div ng-controller="ParentCtrl">
    <div ng-controller="ChildCtrl">
    </div></div>

你可以如此访问父元素:

function ParentCtrl($scope) {
    $scope.cities = ["NY", "Amsterdam", "Barcelona"];}function ChildCtrl($scope) {
    $scope.parentcities = $scope.$parent.cities;}

还有一个更好的方法:因为子元素可以继承父元素的内容,因此你不必调用$parent,上面的实例可以如此重写:

function ParentCtrl($scope) {
    $scope.cities = ["NY","Amsterdam","Barcelona"];}function ChildCtrl($scope) {
    $scope.parentCities = $scope.cities;}


其他方式:

HTML

<div ng-app ng-controller="ParentCtrl as pc">
    <div ng-controller="ChildCtrl as cc">
        <pre>{{cc.parentCities | json}}</pre>
        <pre>{{pc.cities | json}}</pre>
    </div></div>


JS

function ParentCtrl() {
    var vm = this;
    vm.cities = ["NY", "Amsterdam", "Barcelona"];}function ChildCtrl() {
    var vm = this;
    ParentCtrl.apply(vm, arguments); // Inherit parent control

    vm.parentCities = vm.cities;}

如果使用别名,你也可以通过下面这种方式访问父元素内容:

function ChildCtrl($scope) {
    var vm = this;
    vm.parentCities = $scope.pc.cities; // note pc is a reference to the "ParentCtrl as pc"}


如你所见,有不同方式访问父元素

function ParentCtrl() {
    var vm = this;
    vm.cities = ["NY", "Amsterdam", "Barcelona"];}
    function ChildCtrl($scope) {
    var vm = this;
    ParentCtrl.apply(vm, arguments);
    
    vm.parentCitiesByScope = $scope.pc.cities;
    vm.parentCities = vm.cities;}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.20/angular.min.js"></script><div ng-app ng-controller="ParentCtrl as pc">
  <div ng-controller="ChildCtrl as cc">
    <pre>{{cc.parentCities | json}}</pre>
    <pre>{{cc.parentCitiesByScope | json }}</pre>
    <pre>{{pc.cities | json}}</pre>
  </div></div>


可参考:http://stackoverflow.com/questions/21453697/angularjs-access-parent-scope-from-child-controller

转载于:https://my.oschina.net/u/214483/blog/475599

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值