在 AngularJS 中,有两种编写控制器的风格,“控制器作为语法”和“'附加到 $scope' 风格的控制器”(两者都引用自ngController 文档 https://docs.angularjs.org/api/ng/directive/ngController.) StackOverflow 上有几个比较这些风格的问题,例如this 与 AngularJS 控制器中的 $scope https://stackoverflow.com/q/11605917/575530 and 定义的控制器功能之间的性能差异$scope or this- AngularJS https://stackoverflow.com/q/18254869/575530.
我在控制器上有一个方法,需要在模型更新后提示 AngularJS。使用控制器的 $scope 样式我可以这样做:
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
,你仍然可以注入它。假设“控制器为”语法:
myApp.controller('MainController', function($scope) {
this.content = "[Waiting for File]";
$scope.$apply(); // etc.
});
问题是,你真的需要跑步吗$scope.$apply()
那里?假设您在“controller as”语法中正确使用它,它应该看到它:
<div ng-controller="MainController as main">
<div id="content">{{main.content}}</div>
</div>
Then div#content
当您更新您的this.content
变种请注意,您需要小心使用方式this
,所以你可能需要:
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;
};
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)