2014-01-20 71 views
0

我可能会在概念上缺少某些东西,但我明白ng-repeat会创建子范围,但对于我的方案而言,这是不可取的。这是场景。我有一个3WAY绑定到firebase数据集。该对象是一个包含n个子对象的对象。在我现在的代码结构中,我使用ng-repeat来迭代并使用自定义指令来渲染这些对象。问题是这些对象意味着“活”(意味着它们是三向绑定的,最高级别的对象绑定在angularfire $ bind上)。在ng-repeat中保留范围(不需要子范围)

所以在我的情况下,简单的情况是ng-repeat创建的范围与创建它的范围没有隔离。

我在寻找如何做到这一点的想法?或者有关其他方法的建议。

+0

我想你错过了'$ watch'的部分。 'ng-repeat'必须为每个项目创建一个子项目(非隔离)。也许与我们分享一些代码,并告诉我们你已经尝试了什么。 –

回答

1

这会不会是一个完整的答案,但我可以用angularFire部分帮助,并可能是一个角度大师可以为你填空(参见// todo)。

首先,不要试图分享范围。简单地将你想要的变量传递给子范围。既然你想要一个3路绑定,你可以使用&来调用父范围的方法。

例如,要建立这种模式:

<div ng-repeat="(key,widget) in widgets"> 
    <data-widget bound-widget="getBoundWidget(key)"/> 
</div> 

你可以设置你的指令是这样的:

.directive('dataWidget', function() { 
    return { 
     scope: { 
     boundWidget: '&boundWidget' 
     }, 

     /* your directive here */ 

     //todo presumably you want to use controller: ... here 

    } 
}); 

凡& boundWidget调用一个方法在父$范围如下所示:

.controller('ParentController', function($scope, $firebase) { 
    $scope.widgets = $firebase(/*...*/); 
    $scope.getBoundWidget = function(key) { 
     var ref = $scope.widgets.$child(key); 
     // todo, reference $scope.boundWidget in the directive?? 
     ref.$bind(/*** ??? ***/); 
    }; 
}); 

现在你只需要有人来填写//待办事项部分!

0

您仍然可以访问重复中的父范围。你只需要使用$ parent。

控制器

app.controller('MainCtrl', ['$scope', function ($scope) { 
     $scope.someParentScopeVariable = 'Blah' 
     $scope.data = []; 
     $scope.data.push({name:"fred"}); 
     $scope.data.push({name:"frank"}); 
     $scope.data.push({name:"flo"}); 
     $scope.data.push({name:"francis"}); 
}]); 

HTML

<body ng-controller="MainCtrl"> 
    <table> 
     <tr ng-repeat="item in data | filter: search"> 
      <td> 
       <input type="text" ng-model="$parent.someParentScopeVariable"/> 
       <input type="text" ng-model="item.name"> 
      </td> 
     </tr> 
    </table> 
    </body> 

Plunker