什么是$范围的“这个”等价的。在Angular.JS $申请 [英] What is the 'this' equivalent of $scope.$apply in Angular.JS
问题描述
在AngularJS有两种写作风格控制器,在控制器为语法和控制器附加到$范围风格(从的 ngController文档)。有StackOverflow上几个问题比较这些样式,例如的这个VS $范围,AngularJS控制器上和性能差异 $范围
或这个
- AngulrJS
In AngularJS there are two styles of writing controllers, the "the controller as syntax" and the "'attach to $scope' style of controller" (both quotes from the ngController documentation.) There are several questions on StackOverflow comparing these styles, for example this vs $scope in AngularJS controllers and Performance differences between controller functions defined on $scope
or this
- AngulrJS.
我有需要的模型更新后提示AngularJS控制器上的方法。使用控制器的$范围风格我能做到这一点这样的:
I have a method on a controller which needs to prompt AngularJS after a model update. Using the $scope style of controller I can do that thus:
myApp.controller('MainController', ['$scope', function($scope) {
$scope.content = "[Waiting for File]";
$scope.showFileContent = function(fileContent) {
$scope.content = fileContent;
$scope.$apply();
};
}]);
但是,如果我写的用控制器本
But if I write the controller using 'this'
myApp.controller('MainController', function () {
this.content = "[Waiting for File]";
this.showFileContent = function(fileContent){
this.content = fileContent;
};
});
怎么我调用$适用()?
how do I invoke $apply()?
推荐答案
如果你真的需要 $范围
,你仍然可以注入它。假设控制器语法:
If you really need $scope
, you still can inject it. Assuming "controller as" syntax:
myApp.controller('MainController', function($scope) {
this.content = "[Waiting for File]";
$scope.$apply(); // etc.
});
现在的问题是,你真的需要运行 $范围。$适用()
吗?假设你正确使用它在控制器语法,应该看到它:
The question is, do you really need to run $scope.$apply()
there? Assuming you are using it properly in "controller as" syntax, it should see it:
<div ng-controller="MainController as main">
<div id="content">{{main.content}}</div>
</div>
然后 DIV#含量
当你更新你的 this.content
VAR将被更新。你要知道,你需要小心你如何使用这个
,所以你可能需要:
Then div#content
will be updated when you update your this.content
var. Mind you, you need to be careful of how you use this
, so you might need:
myApp.controller('MainController', function($scope) {
var that = this;
this.content = "[Waiting for File]";
this.showFileContent = function(fileContent){
// 'this' might not be set properly inside your callback, depending on how it is called.
// main.showFileContent() will work fine, but something else might not
that.content = fileContent;
};
});
这篇关于什么是$范围的“这个”等价的。在Angular.JS $申请的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!