2015-01-04 30 views
1

我有一個數組,其中包含模板中卡片的對象以循環播放。如果它檢測到本地數據存儲中沒有任何內容,它將創建一個包含對象的數組。否則,它從本地數據存儲中檢索它。按下一個按鈕會使您看到共享相同控制器的另一個視圖。有一個文本框,如果你按下提交按鈕,它會將它拼接到數組。如果檢測到更改,我也有一個監視功能來更新本地數據存儲。Ng-Repeat在陣列更新後沒有更新

問題是在向數組添加內容後ng-repeat不會更新。如果我只是因爲本地數據存儲加載而刷新頁面,纔會出現這種情況。

任何想法?

代碼:controllers.js

.controller('NotesCtrl', function($scope, localStorageService) { 
if (!localStorageService.get("agendaNotes")) { 
    $scope.notes = [{ 
     title: "Civil War Notes" 
    }, { 
     title: "Types of Bacon" 
    }]; 
    //If it exists retrieve it from keystore. 
} else { 
    $scope.notes = localStorageService.get("agendaNotes"); 
} 

$scope.addNote = function(title) { 
    $scope.notes.splice(0, 0, { 
     title: title 
    }) 
}; 

$scope.$watch("notes", function(newVal, oldVal) { 
    if (newVal !== null && angular.isDefined(newVal) && newVal !== oldVal) { 
     localStorageService.add("agendaNotes", angular.toJson(newVal)); 
    } 
}, true); 

}) 

tab.notes.html

​​

新note.html

<ion-view view-title="New Note"> 
    <ion-content> 
     <!-- To Do: 
     - Description 
     - Images (?) 
     --> 
     <form ng-submit="addNote(data.newTitle, data.newDescription); data.newTitle = ''; data.newDescription = ''"> 
      <div class="list"> 
       <div class="list list-inset"> 
        <h3>Note Title:</h1> 
        <label class="item item-input"> 
         <input type="text" placeholder="Title" ng-model="data.newTitle"> 
        </label> 
        <h3>Note Description:</h3> 
        <label class="item item-input"> 
         <input type="text" placeholder="Description" ng-model="data.newDescription"> 
        </label> 
       </div> 
       <button class="button button-block button-positive" type="submit"> 
        Add Note 
       </button> 
      </div> 
     </form> 
    </ion-content> 
</ion-view> 

我曾嘗試$ $範圍適用(。函數(){})方法,並在控制檯中返回一個錯誤:錯誤:[$ rootScope:inprog] $ apply already apply

任何幫助表示讚賞。謝謝

+2

爲了記錄,建議您替換'$ scope.notes.splice(0,0,{...}) ''scope.notes.unshift({...})'' – matewka

+0

您能否提供plnkr? – geckob

回答

1

我認爲這是由於兒童範圍的問題和馬克Rajcok對另一個類似的問題,一個偉大的答案 - Using the same controller on different elements to refer to the same object

總之,他寫道

「每次Angular編譯器在HTML中找到ng-controller時,都會創建一個新的作用域(如果使用ng-view,則每當您轉到不同的路徑時,都會創建一個新的作用域。)

如果你需要在控制之間共享數據通常,服務是您的最佳選擇。將共享數據放入服務中,並將服務注入到控制器中:「

+0

這可能是它,我用一個模式記錄它,它工作得很好。我會研究包括一項服務。 – Drakee510

1

注入$超時(如$ scope),並將您放置的代碼應用到帶有零參數的$ timeout函數調用中。此安全觸發摘要,並「推薦」

$timeout(function() { 
    // model update here 
}) 
+0

我試過了,但是我在chrome錯誤控制檯中得到了這個:2ionic.bundle.js:19387 TypeError:undefined is不是在http:// localhost:8100/lib/ionic/js/ionic.bundle.js:23999:28處的http:// localhost:8100/js/controllers.js:95:20 處的函數 at completeOutstandingRequest (http:// localhost:8100/lib/ionic/js/ionic.bundle.js:12714:10) ,位於http:// localhost:8100/lib/ionic/js/ionic.bundle.js:13094:7 – Drakee510

+0

您在相關區塊周圍寫下的確切代碼是什麼? –