angular笔记 directive scope 调用父scope带参数方法

在使用angular directive的时候,为了不污染环境,我们为给directive自己一个scope,如果这个scope需要使用父类中scope的对象,会使用 = & @三种标示,在开发项目中,我遇到需要调用父类带参数方法的情况,自然而然我想到了使用 &标示符,可是如何进行带参数传递呢?

成功代码:

script:

angular.module('docsIsoFnBindExample', [])
.controller('Controller', ['$scope', '$timeout', function($scope, $timeout) {
  $scope.name = 'Tobias';
  $scope.message = '';
  $scope.hideDialog = function (message) {
    $scope.message = message;
    $scope.dialogIsHidden = true;
    $timeout(function () {
      $scope.message = '';
      $scope.dialogIsHidden = false;
    }, 2000);
  };
}])
.directive('myDialog', function() {
  return {
    restrict: 'E',
    transclude: true,
    scope: {
      'close': '&onClose'
    },
    templateUrl: 'my-dialog-close.html'
  };
});

index.html

<div ng-controller="Controller">
  {{message}}
  <my-dialog ng-hide="dialogIsHidden" on-close="hideDialog(message)">
    Check out the contents, {{name}}!
  </my-dialog>
</div>


my-dialog-close.html

<div class="alert">
  <a href class="close" ng-click="close({message: 'closing for now'})">×</a>
  <div ng-transclude></div>
</div>


我们发现 在my-dialog-colse.html 中,使用了 ng-click="close({message:'closing for now'})",这种传递参数方式让我想起了jsonp方法,这样 在父scope ,hideDialog方法就会拥有message值。

同理 如果我们要使用两个参数,对原有代码进行改变

script:

angular.module('docsIsoFnBindExample', [])
.controller('Controller', ['$scope', '$timeout', function($scope, $timeout) {
  $scope.name = 'Tobias';
  $scope.message = '';
  $scope.hideDialog = function (message,status) {               //多带了一个参数 status
    $scope.message = message;
    $scope.dialogIsHidden = true;
    $timeout(function () {
      $scope.message = '';
      $scope.dialogIsHidden = false;
    }, 2000);
  };
}])
.directive('myDialog', function() {
  return {
    restrict: 'E',
    transclude: true,
    scope: {
      'close': '&onClose'
    },
    templateUrl: 'my-dialog-close.html'
  };
});



index.html

<div ng-controller="Controller">
  {{message}}{{status}}
  <my-dialog ng-hide="dialogIsHidden" on-close="hideDialog(message,status)">     
    Check out the contents, {{name}}!
  </my-dialog>
</div>


my-dialog-close.html

<div class="alert">
  <a href class="close" ng-click="close({message: 'closing for now',status:'1'})">×</a>           //增加status参数
  <div ng-transclude></div>
</div>

注意 :
在index.html 中ng-close="hideDialog( message,status)"  这俩参数名(message,status) 必须和 my-dialog-close.html中 ng-click="close({ message:'close for now', status:'1'})"相同

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值