2014-01-20 73 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