AngularJS 1.x 中的递归组件
Recursive Components in AngularJS 1.x
终于尝试学习 AngularJS 但我不太明白如何使组件递归工作。我有一个简单的 example 未按预期呈现。
HTML
<body ng-app="myApp" ng-controller="myCtrl as vm">
<nested-list list="vm.list"></nested-list>
</body>
JavaScript
angular.module('myApp', [])
.controller('myCtrl', ['$scope', function($scope) {
$scope.list = [
{ "name": "Item 1" },
{ "name": "Item 2",
"subItems": [
{ "name": " Item 2.1" }
]
},
{ "name": "Item 3",
"subItems": [
{ "name": " Item 3.1" },
{ "name": "Item 3.2",
"subItems": [
{ "name": "Item 3.2.1" },
{ "name": "Item 3.2.2" }
]
}
]
}];
}])
.component('nestedList', {
bindings: {
list: '<'
},
template: `
<div ng-repeat="item in $ctrl.list" >
<div> {{item.name}} </div>
<nested-list list="item.subItems"></nested-list>
</div>
`
});
毫无疑问,因为我遗漏了一些明显的东西,来自应用程序主控制器的列表 myCtrl
没有绑定到根组件。如果有人能提供见解,我将不胜感激。
斯蒂芬
当您使用 controllerAs
时,您应该将值绑定到控制器 this
(上下文),而不是将值绑定到 $scope
。
.controller('myCtrl', [function() {
var vm = this;
vm.list = [ ..];
}]);
终于尝试学习 AngularJS 但我不太明白如何使组件递归工作。我有一个简单的 example 未按预期呈现。
HTML
<body ng-app="myApp" ng-controller="myCtrl as vm">
<nested-list list="vm.list"></nested-list>
</body>
JavaScript
angular.module('myApp', [])
.controller('myCtrl', ['$scope', function($scope) {
$scope.list = [
{ "name": "Item 1" },
{ "name": "Item 2",
"subItems": [
{ "name": " Item 2.1" }
]
},
{ "name": "Item 3",
"subItems": [
{ "name": " Item 3.1" },
{ "name": "Item 3.2",
"subItems": [
{ "name": "Item 3.2.1" },
{ "name": "Item 3.2.2" }
]
}
]
}];
}])
.component('nestedList', {
bindings: {
list: '<'
},
template: `
<div ng-repeat="item in $ctrl.list" >
<div> {{item.name}} </div>
<nested-list list="item.subItems"></nested-list>
</div>
`
});
毫无疑问,因为我遗漏了一些明显的东西,来自应用程序主控制器的列表 myCtrl
没有绑定到根组件。如果有人能提供见解,我将不胜感激。
斯蒂芬
当您使用 controllerAs
时,您应该将值绑定到控制器 this
(上下文),而不是将值绑定到 $scope
。
.controller('myCtrl', [function() {
var vm = this;
vm.list = [ ..];
}]);