gpt4 book ai didi

javascript - 如何使用 ControllerAs 语法手动更新 AngularJS View ?

转载 作者:数据小太阳 更新时间:2023-10-29 05:18:53 24 4
gpt4 key购买 nike

我正在开发一个带有可排序、可停靠、可 float 小部件的仪表板。我正在使用的控件之一在结束 body 标记之前在 DOM 底部生成 float 小部件作为 HTML。这有效地从窗口控件中生成它们的 Controller 范围中删除了在窗口控件中完成的操作。

我正在使用可用的 controllerAs 语法开发此仪表板 Controller ,但我不知道如何在外部组件执行影响数据的操作时使用此语法有效地更新 View 风景?

注意:这不是我面临的唯一一个迫使我手动更新主视图的问题。页面上其他地方也有执行影响 View 的操作的指令。

理想情况下,我永远不必手动更新 View ,因为我将使用在影响摘要循环的内置 Angular 命令中发生的所有命令——但这对我来说不是一个选项。

所以...如果我使用 $scope 我可以简单地做:

$scope.$digest

或者

$scope.$apply

但是我如何使用 Controller 实现同样的效果呢?

var vm = this;
vm.array = [item, item];
vm.something = something;

//External something changes something on a vm.variable

vm.update! //How??

最佳答案

使用“as”定义在 View 中引用 Controller 范围的方式。

所以这样:

<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
</body>

app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
});

等于:

<body ng-controller="MainCtrl as main">
<p>Hello {{main.name}}!</p>
</body>

你的 Controller :

app.controller('MainCtrl', function($scope) {
this.name = 'World';
});

DEMO

所以基本上你应该能够像在 $scope 上那样调用 this.$digestthis.$apply

更新

经过一些搜索,我认为正确的解决方案应该是使用 $scope.apply()$scope.digest()

主要资源:
AngularJS’s Controller As and the vm Variable
a comment提出你同样的问题,作者重播:

You can use $scope.$apply() in that case and just inject $scope for that purpose (still using vm for everything else). However, if you switch fro using ajax to using Angular's $http, then you won't need to call $apply as angular's $http does that for you. That's what I recommend

我找到的其他资源:

关于javascript - 如何使用 ControllerAs 语法手动更新 AngularJS View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27256136/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com