什么是'这个'相当于$ scope。$适用于AngularJS?

时间:2014-12-15 18:00:35

标签: angularjs

在AngularJS中有两种编写控制器的样式,“控制器作为语法”和“'附加到$ scope'控制器样式”(两个引用来自ngController documentation。)有几个问题关于StackOverflow比较这些样式,例如this vs $scope in AngularJS controllersPerformance differences between controller functions defined on $scope or this - AngularJS

我在控制器上有一个方法,需要在模型更新后提示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()?

1 个答案:

答案 0 :(得分:4)

如果你真的需要$scope,你仍然可以注射它。假设"控制器为"语法:

myApp.controller('MainController', function($scope) {
   this.content = "[Waiting for File]";
   $scope.$apply(); // etc.
});

问题是,你真的需要在那里运行$scope.$apply()吗?假设您在"控制器中正确使用它"语法,它应该看到它:

<div ng-controller="MainController as main">
  <div id="content">{{main.content}}</div>
</div>

当您更新div#content var时,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;
   };
});