[英]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.