angularjs 子父controller交互问题

关于angularjs,$scope 交互时最近遇到几个问题

对$scope直接进行赋值

  <div ng-controller="SomeCtrl">
    {{ someBareValue }}
    <button ng-click="someAction()">Communicate </button>
    <div ng-controller="ChildCtrl">
      {{ someBareValue }}
      <button ng-click="childAction()">Communicate </button>
    </div>
  </div>

  <script>
    angular.module('myApp', [])
    .controller('SomeCtrl', function($scope) {
      // anti-pattern, bare value
      $scope.someBareValue = 'hello computer';
      // set actions on $scope itself, this is okay
      $scope.someAction = function() {
        $scope.someBareValue = 'hello human, from parent';
      };
    })
    .controller('ChildCtrl', function($scope) {
      $scope.childAction = function() {
        $scope.someBareValue = 'hello human, from child';
      };
    });
  </script>

效果:子controller只能改变子的,父的可以两个一起变,但是子的改变过后父的就无法再另其改变


对$scope进行对象的赋值引用:

<div ng-controller="SomeCtrl">
    {{ someModel.someValue }}
    <button ng-click="someAction()">Communicate to child</button>
    <div ng-controller="ChildCtrl">
      {{ someModel.someValue }}
      <button ng-click="childAction()">Communicate to parent</button>
    </div>
  </div>

  <script>
    angular.module('myApp', [])
    .controller('SomeCtrl', function($scope) {
      // best practice, always use a model
      $scope.someModel = {
        someValue: 'hello computer'
      }
      $scope.someAction = function() {
        $scope.someModel.someValue = 'hello human, from parent';
      };
    })
    .controller('ChildCtrl', function($scope) {
      $scope.childAction = function() {
        $scope.someModel.someValue = 'hello human, from child';
      };
    });
  </script>
效果:这个就是两个都变。。。


总结:在js中,对象,数组,函数是一个引用,类似浅拷贝。但是数值,字符串是值赋值。如果将模型对象的某个属性设置为字符串,它会通过引用进行共享,因此在子的改变也会改变父的。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值