AngularJS中$ scope.$ apply的"this"等效项是什么?

编程入门 行业动态 更新时间:2024-10-25 20:21:53
本文介绍了AngularJS中$ scope.$ apply的"this"等效项是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在AngularJS中,有两种编写控制器的样式,控制器作为语法"和'附加到$ scope'的控制器样式"(均引自 ngController文档.)在StackOverflow上比较这些样式有几个问题,例如在AngularJS控制器中,此vs $ scope 和在$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"等效项是什么?

本文发布于:2023-11-13 23:43:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1585635.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:scope   AngularJS   quot   apply

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!