什么是';这';相当于$scope.$在AngularJS中应用?
在AngularJS中,有两种编写控制器的样式,“控制器作为语法”和“附加到$scope”样式的控制器(都引用自)。关于StackOverflow,比较这些样式有几个问题,例如和 我在控制器上有一个方法,需要在模型更新后提示AngularJS。使用控制器的$scope样式,我可以这样做:什么是';这';相当于$scope.$在AngularJS中应用?,angularjs,Angularjs,在AngularJS中,有两种编写控制器的样式,“控制器作为语法”和“附加到$scope”样式的控制器(都引用自)。关于StackOverflow,比较这些样式有几个问题,例如和 我在控制器上有一个方法,需要在模型更新后提示AngularJS。使用控制器的$scope样式,我可以这样做: myApp.controller('MainController', ['$scope', function($scope) { $scope.content = "[Waiting for File]
myApp.controller('MainController', ['$scope', function($scope) {
$scope.content = "[Waiting for File]";
$scope.showFileContent = function(fileContent) {
$scope.content = fileContent;
$scope.$apply();
};
}]);
但是如果我用“this”写控制器
myApp.controller('MainController', function () {
this.content = "[Waiting for File]";
this.showFileContent = function(fileContent){
this.content = fileContent;
};
});
如何调用$apply()?如果您确实需要
$scope
,您仍然可以注入它。假设“controller as”语法:
问题是,您真的需要在那里运行$scope.$apply()
?假设您在“controller as”语法中正确使用它,它应该会看到:
<div ng-controller="MainController as main">
<div id="content">{{main.content}}</div>
</div>
谢谢@deitch。我也不希望需要使用
$source.$apply()
,但是。哦,我明白了!您正在调用showFileContent()
以响应FileReader
事件,因此回调在上下文之外执行。是吗?是的,你的onchange
在角度上下文之外执行东西。我将就此发表评论。这是一个单独的问题。您可以使用$apply
将异步任务包装为$q
,从而绕过此问题。你考虑过吗?
<div ng-controller="MainController as main">
<div id="content">{{main.content}}</div>
</div>
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;
};
});