[英]Angular equivalent of AngularJS' ng-init with Default Values within Scope
我正在從NGJS過渡到NG,並嘗試重新編碼我以前的應用程序以進行練習。
我偶然發現了新的NgInit,其中在Angular的Component中完成了初始化。
我想要實現的是在范圍內初始化一個值,以用作隱藏和取消隱藏HTML元素的切換。 我正在嘗試解決此問題而無需在ngOnInit() {}
循環來初始化數組內的每個對象。 ( 請參見ng-init
ng-repeat
塊中的ng-init
)
以下是我要實現的方案的工作副本:
angular.module("app", []) .controller("controller", function($scope) { $scope.init = function() { $scope.modules = [ { label: 'Module A', children: [ 'Module A - 1', 'Module A - 2', 'Module A - 3' ] }, { label: 'Module B', children: [ 'Module B - 1', 'Module B - 2', 'Module B - 3' ] }, { label: 'Module C', children: [ 'Module C - 1', 'Module C - 2', 'Module C - 3' ] } ]; }; });
.child { padding-left: 24px; padding-top: 8px; padding-bottom: 8px; } .parent { padding: 8px; }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <body ng-app="app" ng-controller="controller" ng-init="init()"> <div class="parent" ng-repeat="module in modules" ng-init="toggle=true"> {{module.label}} <button ng-click="toggle = !toggle">toggle</button> <span ng-if="toggle" id="child-group"> <div class="child" ng-repeat="child in module.children"> {{child}} </div> </span> </div> </body>
如果您願意,可以使用Plunker: https ://plnkr.co/edit/JDBBPLkr21wxSe2dlRBv?p = preview
您可以這樣做。 您可以使用* ngFor遍歷數組。 該按鈕切換相應的布爾值,該值定義是否顯示您的元素(使用* ngIf指令)
@Component({
selector: 'my-app',
template: `
<div *ngFor="let module of modules; let i = index">
<button (click)="show[i] = !show[i]">toggle</button>
<h2>{{module.label}}</h2>
<div *ngIf="show[i]">
<li *ngFor="let child of module.children">
{{child}}
</li>
</div>
</div>
`,
})
然后初始化變量:
export class AppComponent {
modules:any[];
show:boolean[];
constructor() {
this.modules = [
{
label: 'Module A',
children: [
'Module A - 1',
'Module A - 2',
'Module A - 3'
]
},
{
label: 'Module B',
children: [
'Module B - 1',
'Module B - 2',
'Module B - 3'
]
},
{
label: 'Module C',
children: [
'Module C - 1',
'Module C - 2',
'Module C - 3'
]
}
];
this.show = this.modules.map(()=>true);
}
}
我不理解您的要求,您能更好地解釋一下自己嗎? 你為什么不嘗試使用@component ...
@Component({
selector: 'tag-selector',
templateUrl: './pagina.html',
styleUrls: ['./pagina.css']
})
export class Controller{
your code
}
編輯:
如果您從Init中聲明$ scope,它仍然可以正常工作
angular.module("app", [])
.controller("controller", function($scope) {
$scope.init = function() {
};
$scope.modules = [{
label: 'Module A',
children: [
'Module A - 1',
'Module A - 2',
'Module A - 3'
]
}, {
label: 'Module B',
children: [
'Module B - 1',
'Module B - 2',
'Module B - 3'
]
}, {
label: 'Module C',
children: [
'Module C - 1',
'Module C - 2',
'Module C - 3'
]
}];
});
很抱歉,但是我不確定我是否完全理解這個問題...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.