2

我是新來Angular.js並試圖遵循幾個教程來了解如何雙向綁定contenteditable元素在ng-repeat

我在控制器之間使用一個共享「存儲」,例如,

pushupsApp.factory('grids', function() { 
    return [ 
     ... 
     { 
     'id': 1409875200000, // 2014-09-05 
     'sets': [ 
      5, 
      10, 
      15, 
      20, 
      25, 
      30 
     ] 
     }, 
     { 
     'id': 1409912060233, // 2014-09-05 11:14 
     'sets': [ 
      5, 
      10, 
      15, 
      20, 
      25, 
      30 
     ] 
     } 
    ]; 
    }); 

    pushupsApp.controller('indexController', function ($scope, grids) { 
    $scope.grids = grids; 
    }); 

這似乎工作得很好;如果我在一個控制器中更改$scope.grids,那麼此更改在所有其他控件中都是持久的,直到我刷新頁面爲止。

this教程,並在Angular.js docs的例子,我有以下控制器和指令:

pushupsApp.controller('gridController', 
    function ($scope, $routeParams, $filter, grids) { 
     var now = new Date(Date.now()); 

     $scope.date = $filter('date')(now, 'yyyy-MM-dd'); 
     $scope.grids = $filter('filter')(grids, {'id':$scope.date}, 
     function (actual, expected) { 
      return angular.equals($filter('date')(actual, 'yyyy-MM-dd'), 
      $filter('date')(expected, 'yyyy-MM-dd')); 
     }); 
    }).directive('contenteditable', function() { 
    return { 
     restrict: 'A', 
     require: 'ngModel', 
     link: function (scope, element, attributes, ngModel) { 
     ngModel.$render = function() { 
      element.html(ngModel.$viewValue || ''); 
     }; 

     element.bind('keyup', function() { 
      scope.$apply(function() { 
      ngModel.$setViewValue(element.html); 
      }); 
     }); 
     } 
     }; 
    }); 

的問題

我的本意是,當我編輯的contenteditable元素在ng-repeat$scope.grids更新也是鏡像編輯,在事件觸發後。

$scope.grids雖然沒有更新。我試圖研究自己可能發生的事情,但由於我對Angular.js非常陌生,我實在不知道我應該尋找什麼!我發現的一切都表明我現在的代碼應該可以工作。

爲了完整起見,我有以下模板太:

<script type="text/ng-template" id="grid.html"> 
    <p>{{date}}</p> 
    <ul> 
    <li ng-repeat="grid in grids"> 
     <p ng-if="grids.length > 1">{{grid.id | date:'shortTime'}}</p> 
     <ul> 
     <li contenteditable="" ng-model="grids" ng-repeat="set in grid.sets"> 
      {{set}} 
     </li> 
     </ul> 
    </li> 
    </ul> 
</script> 

最終,我的「店」將是持久的,但現在我很高興爲它只能是每個會話。

任何幫助將不勝感激,以及任何其他指針,關於我的Angular.js代碼一般和什麼問題可能是!

謝謝你的幫助! Jon

This Might Help ?!

我注意到,當我將我的模板中的ng-model屬性更改爲grid.sets時,keyup事件觸發$scope.grids更新。 但是,集合的整個列表從DOM和$scope.grids中被刪除。可能在這裏發生的事情可能有助於解決問題;希望!

回答

0

繼我的發現(見這可能幫助)我突然非常接近解決方案!

由於整個數據塊都從$scope.grids中刪除,我現在知道我可以將這個塊縮小到contenteditable元素和'store'中的相應數據塊。

ng-template屬性更改爲grid.sets[$index]就是這樣做的。

原來正在從DOM中刪除的元素,因爲我在這裏失去了括號:

  scope.$apply(function() { 
      // ngModel.$setViewValue(element.html); 
      ngModel.$setViewValue(element.html()); 
      }); 

這只是粗心大意。contenteditable元素在每次往返之後都會丟失focus,所以我改爲將事件改爲在blur上觸發。

問題,解決了:-)

我希望這有助於喬恩