Angularjs值不更新

时间:2016-02-03 01:22:59

标签: html angularjs

我知道有人问过类似的问题,但这些问题并不适用于我的案子。我在控制器中定义了一些变量,并在面板中显示它们的值。与部件相关的控制器是这样的:

var vm = this;
vm.wellId = "id";
vm.wellSeq = "sequence";
vm.onWellSelected = onWellSelected;
...
function onWellSelected(wells) {
    ...
    vm.wellId = wells[0]["id"];
    vm.wellSeq = wells[0]["sequence"];
    ...
}

我的html组件是这样的:

<div plate id="plate-layout"
    on-well-selected="vm.onWellSelected(wells)">
</div>
<ul class="list-group" style="width: 400px; overflow: auto">
    <li class="list-group-item">{{vm.wellId}}</li>
    <li class="list-group-item">{{vm.wellSeq}}</li>
</ul>

我检查了源并在函数onWellSelected中设置了断点:vm.wellId和vm.wellSeq确实在操作后更改为正确的值,但是无法显示新值。盘子的定义涉及很多其他js文件,所以这里不容易显示,但是板块本身是一个指令,有两个服务的支持。可能是什么原因?谢谢!

2 个答案:

答案 0 :(得分:5)

Sorry I'm new to Angular so took me a while to find this:

$scope.$apply();

Put it after the modification part and then the value is updated on the page.

EDIT:

Just a follow-up: if use this: $scope.$apply() or $scope.$digest(), then I'll get this error: $digest already in progress; but if I remove it, the value won't get updated. So I refer to this post here: Prevent Error, and now it's working fine without the error message. Hope this can help those facing the same issue.

答案 1 :(得分:1)

var app = angular.module('myApp', []);

app.controller("myCtrl", function () {
  var vm = this;
  vm.wellId = "id";
  vm.wellSeq = "sequence";

  vm.onWellSelected = function (wells) {
    vm.wellId = wells[0]["id"];
    vm.wellSeq = wells[0]["sequence"];
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp">
  <div ng-controller="myCtrl as vm">
    <span>{{vm.wellId}}</span>
    <span>{{vm.wellSeq}}</span>
    <button ng-click="vm.onWellSelected([{id: 'new id', sequence: 'new sequence'}])">Select Well</button>
  </div>
</div>