我正在使用angularJs中的复选框选项制作嵌套树结构。
我的后端对象如下。
{ "2": { "id": 2, "name": "Under Graduate", "slug": "under-graduate", "parent_id": 0, "level": 0, "path": "0", "show": false, "selected": false, "children": { "3": { "id": 3, "name": "B.Com", "slug": "b-com", "parent_id": 2, "level": 1, "path": "2", "show": false, "selected": false, "children": { "4": { "id": 4, "name": "Commerce", "slug": "commerce", "parent_id": 3, "level": 2, "path": "2\/3", "show": false, "selected": false } } } } }}
我已将同一对象分配给具有不同名称的2 $ scope变量
$scope.a = object; $scope.b = object;现在我已经用ng-include在li元素中使用了ng-repeat,如下所示
<li ng-repeat="a in a.children" ng-include="'a_tree_renderer.html'"></li>使用与另一个变量相同的方法(b)
<li ng-repeat="b in b.children" ng-include="'b_tree_renderer.html'"></li>在这两个模板中,它们是一个用于展开和查看所有孩子的选项。
与树算法相关的所有内容都可以正常工作,除非我在一个模板上执行此操作。 b,不知何故模板(a)的索引也会发生变化,也就是说,如果从第二个模板扩展选项,第一个模板上的同一个扩展,反之亦然。
I am making a nested tree structure with checkbox option in angularJs.
My object from the backend is as follows.
{ "2": { "id": 2, "name": "Under Graduate", "slug": "under-graduate", "parent_id": 0, "level": 0, "path": "0", "show": false, "selected": false, "children": { "3": { "id": 3, "name": "B.Com", "slug": "b-com", "parent_id": 2, "level": 1, "path": "2", "show": false, "selected": false, "children": { "4": { "id": 4, "name": "Commerce", "slug": "commerce", "parent_id": 3, "level": 2, "path": "2\/3", "show": false, "selected": false } } } } }}
I have assigned the same object to 2 $scope variable with different names
$scope.a = object; $scope.b = object;Now i have used ng-repeat inside the li element with ng-include as follows
<li ng-repeat="a in a.children" ng-include="'a_tree_renderer.html'"></li>Using the same method with another variable(b)
<li ng-repeat="b in b.children" ng-include="'b_tree_renderer.html'"></li>Inside both the template their is an option given to expand and view all the children.
Everything related to the tree algo works fine except when i perform this operation on one template ex. b, Somehow the template (a) index also changes, i.e if a expand an option from the second template the same thing on the first template expands, and vice versa.
最满意答案
通过赋值$scope.a = object; 和$scope.b = object; , $scope.a和$scope.b引用同一个对象。 因此,修改其中一个会影响另一个。
如果您希望$scope.a和$scope.b是独立的,则可以使用$scope.b创建对象的深层副本,以便每个范围变量引用该对象的不同副本。 这样,当您在$scope.a或$scope.b上更改任何内容时,另一个不会受到影响。
By assigning $scope.a = object; and $scope.b = object;, both $scope.a and $scope.b reference the same object. Therefore, modifying one of them will affect the other.
If you would like $scope.a and $scope.b to be independent, you could create a deep copy of the object so that each scope variable references a different copy of the object, by using angular.copy. That way, when you change anything on $scope.a or $scope.b, the other will not be affected.
更多推荐
发布评论