‘@’和'='倒是好理解,有沒有一個必須使用'&'的場景?
<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>