javascript – 当AngularJS中的模型更新时,视图不会更新

前端之家收集整理的这篇文章主要介绍了javascript – 当AngularJS中的模型更新时,视图不会更新前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我已经阅读了这个问题的线程,例如: The view is not updated in AngularJS,但我仍然无法理解如何将它应用于我的简单示例. @H_301_2@我有这个功能

function MyPageView($scope) {
  var myModel = new MyModel();
  $scope.myModel = myModel;
}
@H_301_2@当myModel在代码中的其他位置更新时(当用户点击,交互,发送XHR请求时),它不会更新我的视图.我知道我需要用$apply做点什么,但我不知道在哪里以及如何做.

@H_301_2@有人可以向我解释如何为这个简单的用例解决这个问题?

@H_301_2@我的模型看起来像这样(如果问题是必要的) – 它内部没有AngularJS代码

var MyModel = function() {
  var _this = this;
  ...
  _this.load = function(){...};
  _this.updateModel = function(){...};
  ...
  return _this;
}
@H_301_2@添加JSfiddle示例:http://jsfiddle.net/DAk8r/2/

解决方法

你的问题的关键在于你正试图将AngularJS与一种非常传统的“jQuery-soup风格”JavaScript模式混合在一起.在Angular中,您应该始终使用指令来执行DOM操作和交互(包括点击).在这种情况下,您的代码应该更像以下内容
<div ng-controller="myModelCtrl">
  <div>Number is {{myModel.number}}</div>
  <a ng-click="myModel.updateNumber()">Update Number</a>
</div>
function myModelCtrl($scope) {
   var myModel = new MyModel();
   $scope.myModel = myModel;
}

function MyModel() {
  var _this = this;

  _this.number = 0;

  _this.updateNumber = function() {
     _this.number += 1;
    alert('new number should display ' + _this.number);
  }

  return _this;
}
@H_301_2@请注意,我们使用Angular的内置ng-click指令,而不是使用jQuery设置手动点击处理程序.这允许我们绑定到Angular范围生命周期,并在用户单击链接时正确更新视图.

@H_301_2@这是AngularJS FAQ的报价;我加粗了一个可能帮助你打破习惯的部分.

Common Pitfalls

@H_301_2@The Angular support channel (#angularjs on Freenode) sees a number of recurring pitfalls that new users of Angular fall into. This document aims to point them out before you discover them the hard way.

DOM Manipulation

@H_301_2@Stop trying to use jQuery to modify the DOM in controllers. Really. That includes adding elements,removing elements,retrieving their contents,showing and hiding them. Use built-in directives,or write your own where necessary,to do your DOM manipulation. See below about duplicating functionality.

@H_301_2@If you’re struggling to break the habit,consider removing jQuery from your app. Really. Angular has the $http service and powerful directives that make it almost always unnecessary. Angular’s bundled jQLite has a handful of the features most commonly used in writing Angular directives,especially binding to events.

@H_301_2@最后,在这个例子中,使用这种技术:http://jsfiddle.net/BinaryMuse/xFULR/1/

猜你在找的JavaScript相关文章