Heim > Fragen und Antworten > Hauptteil
‘@’和'='倒是好理解,有没有一个必须使用'&'的场景?
<body ng-app="myApp" ng-init="content='abc'">
<p ng-controller="myController" >
<input type="text" ng-model="content" />
<p my-directive my-title="title" my-content="content" ></p>
</p>
</body>
<script type="text/javascript">
var myApp = angular.module('myApp', [])
.directive('myDirective', function($rootScope) {
return {
priority:1000,
restrict: 'A',
replace: true,
scope: {
myTitle:'@',
myContent: '='
},
template: '<p><h2>{{myTitle}}</h2><p>from myDirective:{{myContent}}</p></p>'
};
})
.controller('myController',function($scope){
$scope.content = 'from controller';
});
</script>
希望可以提供一个demo。
phpcn_u15822017-05-15 16:52:53
&的用法: 传递一个来自父scope的函数,稍后调用
什么情况下用:当我们在directive里需要调用controller的方法时,一般我们会在directive里传一些参数到controller的方法里
实际案例:比如一个树形结构的directive,我们选中某个节点后,需要在controller对这个节点进行更一步的操作,比如根据选中的节点去服务器取数据。所以在directive里面,我们需要把选中的节点传到controller里面。
Demo
Demo代码:
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>
my-dialog-close.html:
<p class="alert">
<a href class="close" ng-click="close()">×</a>
<p ng-transclude></p>
</p>