问题描述
在AngularJS中,有两种编写控制器的样式,控制器作为语法"和'附加到$ scope'的控制器样式"(均引自 ngController文档.)在StackOverflow上比较这些样式有几个问题,例如和在$scope
上定义的控制器功能之间的性能差异或this
-AngularJS .
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
- AngularJS.
我在控制器上有一个方法,该方法需要在模型更新后提示AngularJS.使用$ scope样式的控制器,我可以这样:
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();
};
}]);
但是如果我使用'this'编写控制器
But if I write the controller using 'this'
myApp.controller('MainController', function () {
this.content = "[Waiting for File]";
this.showFileContent = function(fileContent){
this.content = fileContent;
};
});
如何调用$ apply()?
how do I invoke $apply()?
推荐答案
如果确实需要$scope
,您仍然可以注入它.假设"controller as"语法:
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.
});
问题是,您真的需要在那里运行$scope.$apply()
吗?假设您以"controller as"语法正确使用了它,那么应该可以看到它:
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>
然后,当您更新this.content
变量时,div#content
将被更新.提醒您,您需要小心使用this
的方式,因此您可能需要:
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;
};
});
这篇关于AngularJS中$ scope.$ apply的"this"等效项是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!