我有这个功能:
function MyPageView($scope) { var myModel = new MyModel(); $scope.myModel = myModel; }
当myModel在代码中的其他位置更新时(当用户点击,交互,发送XHR请求时),它不会更新我的视图.我知道我需要用$apply做点什么,但我不知道在哪里以及如何做.
有人可以向我解释如何为这个简单的用例解决这个问题?
我的模型看起来像这样(如果问题是必要的) – 它内部没有AngularJS代码:
var MyModel = function() { var _this = this; ... _this.load = function(){...}; _this.updateModel = function(){...}; ... return _this; }
添加JSfiddle示例:http://jsfiddle.net/DAk8r/2/
解决方法
<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; }
请注意,我们使用Angular的内置ng-click指令,而不是使用jQuery设置手动点击处理程序.这允许我们绑定到Angular范围生命周期,并在用户单击链接时正确更新视图.
这是AngularJS FAQ的报价;我加粗了一个可能帮助你打破习惯的部分.
Common Pitfalls
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
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.
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.
最后,在这个例子中,使用这种技术:http://jsfiddle.net/BinaryMuse/xFULR/1/