扫码关注官方订阅号
‘@’和'='倒是好理解,有没有一个必须使用'&'的场景?
希望可以提供一个demo。
走同样的路,发现不同的人生
&的用法: 传递一个来自父scope的函数,稍后调用
什么情况下用:当我们在directive里需要调用controller的方法时,一般我们会在directive里传一些参数到controller的方法里
实际案例:比如一个树形结构的directive,我们选中某个节点后,需要在controller对这个节点进行更一步的操作,比如根据选中的节点去服务器取数据。所以在directive里面,我们需要把选中的节点传到controller里面。
Demo
Demo代码:
javascriptangular.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' }; });
javascript
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' }; });
html<p ng-controller="Controller"> {{message}} <my-dialog ng-hide="dialogIsHidden" on-close="hideDialog(message)"> Check out the contents, {{name}}! </my-dialog> </p>
html
<p ng-controller="Controller"> {{message}} <my-dialog ng-hide="dialogIsHidden" on-close="hideDialog(message)"> Check out the contents, {{name}}! </my-dialog> </p>
my-dialog-close.html:
<p class="alert"> <a href class="close" ng-click="close()">×</a> <p ng-transclude></p> </p>
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
&的用法: 传递一个来自父scope的函数,稍后调用
什么情况下用:当我们在directive里需要调用controller的方法时,一般我们会在directive里传一些参数到controller的方法里
实际案例:比如一个树形结构的directive,我们选中某个节点后,需要在controller对这个节点进行更一步的操作,比如根据选中的节点去服务器取数据。所以在directive里面,我们需要把选中的节点传到controller里面。
Demo
Demo代码:
my-dialog-close.html: