[英]How to pass parameters in nested controllers in Angular JS
我遇到從控制器中的REST API獲取一些數據的情況,我使用ng-repeat渲染了這些數據。 然后在該循環中,我需要運行另一個控制器,從早期控制器傳遞數據,對其執行一些操作,然后再次對其執行ng-repeat。
當我這樣做時,“檢查元素”顯示保留在父控制器參數中的值。 但是,傳遞給嵌套控制器的值實際上是變量名。
源代碼:
HTML:
<div class="checkbox" ng-repeat="bird in birds">
<table>
<tr>
<td>
<a ng-href="/birds/{{bird.Image}}" rel="shadowbox"><img ng-src="/birds/{{bird.Image}}" height="200" width="200"></img></a>
<div ng-controller="imageController" model="{{ bird.AdditionalImages }}">More Images: {{ imageString }}
<div ng-repeat="image in images">
<a ng-href="/birds/{{image}}" rel="shadowbox[{{ bird.Image }}]">a</a>
</div>
</div>
</td>
<td>
<table>
<tr>
<td>
<b>{{ bird.CommonName }}</b>
</td>
</tr>
<tr>
<td>
Spotted at: {{ bird.SpottedAt }}
</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
JavaScript(用於嵌套控制器):
anekchidiya.controller('imageController', function($scope, $attrs) {
$scope.imageString = $attrs.model;
console.log("images: " + $scope.imageString);
});
您可以通過將范圍傳遞給指令來執行此操作,並創建一個隔離的范圍 。
例如 :
控制者
(function(){
function Controller($scope) {
$scope.data = [{
name: 'john',
age: '26'
}, {
name: 'paul',
age: '24'
}, {
name: 'titi',
age: '32'
}];
}
angular
.module('app', [])
.controller('ctrl', Controller);
})();
指示
(function(){
function customDirective() {
return{
restrict: 'AE',
template: '<h3>Age : {{age}}</h3>',
scope: {
age: '='
}
};
}
angular
.module('app')
.directive('customDirective', customDirective);
})();
例如,您可以通過傳遞一些數據來將指令調用到ngRepeat
中:
的HTML
<body ng-app="app" ng-controller="ctrl">
<div ng-repeat="item in data">
<h2>Name : {{item.name}}</h2>
<custom-directive age="item.age"></custom-directive>
</div>
</body>
因此,隔離范圍的典型用法是在創建完整組件,小部件等的指令中...
因此,您將能夠構建一些自定義組件,並傳遞特定數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.