在使用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>
<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>
<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'})"相同