AngularJS不应用更改,使用$ apply结束错误

时间:2014-06-29 10:53:57

标签: javascript angularjs

我是AngularJS的新手,我的第一个项目有问题: 如果我更新特殊的$ scope-variable,则不会应用更改。更改另一个$ scope-variable工作正常。我尝试使用$ scope。$ apply但它说“$ apply已在进行中”。使用ng-inspector(Chrome扩展程序),我发现新值已分配给$ scope-variable,但ng-repeat不应用此更改... 这是代码(coffeescript)。有问题的变量名为“ingreds”:

angular.module 'magicPeda', ['ngDragDrop']
.controller 'IngredientsCtrl', ($scope, $http) ->
  $http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded"
  base = null
  $http.get('/base').then (iResponse) ->
     base = iResponse.data
     $scope.ingreds = base
     $scope.combination = []
  $scope.cook = ->
    ids = []
    for ingreds in ($scope.combination)
      ids.push ingreds._id
    ids = JSON.stringify ids
    IdString = $.param({ingredids: ids})
    request = $http({
      method: "POST",
      url: "/cook",
      data: IdString,
      headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    }).then (response) ->
      base.push response.data
      $scope.ingreds = base
      $scope.combination = []
  $scope.reset = ->
    $scope.ingreds = base
    $scope.combination = []

和html部分:

  <div class="container" ng-controller="IngredientsCtrl">
    <table class="table" >
      <tr ng-repeat="ingredient in ingreds">
        <td>
          <img ng-src="/images/{{ingredient.pic}}" data-drag="true" ng-model="ingredient"
          -jqyoui-options="{revert: 'invalid'}" jqyoui-draggable="{animate:true}"  ng-hide="!ingredient.name"></img>
          {{ingredient.name}}
        </td>
      </tr>
    </table>
    <div class="thumbnail" data-drop="true" ng-model="combination" jqyoui-droppable="{multiple:true}" style='height:150px; bottom: 0px;'>
      <div class="btn-group">
        <button type="button" class="btn btn-danger" style="height: 100%" ng-click="reset()" ng-show="combination[0].name">Reset</button>
        <button type="button" class="btn btn-default" ng-repeat="item in combination track by $index">
          <img ng-show="item.name" data-drag="false" data-jqyoui-options="{revert: 'invalid', helper: 'clone'}" ng-model="combination" jqyoui-draggable="{index: {{$index}}, placeholder: 'keep'}" ng-src="/images/{{item.pic}}" />
        </button>
        <button type="button" class="btn btn-success" style="height: 100%" ng-click="cook()">Cook!</button>
      </div>
    </div>
  </div>

1 个答案:

答案 0 :(得分:0)

如果您发布了javascript而不是咖啡脚本会更容易。但我认为问题在于您似乎是通过基本局部变量更新范围变量。如果您在延迟的promise中解析时直接更新scope.ingreds变量,那么angular应该将其视为其摘要周期的一部分,并根据需要更新视图。