【发布时间】:2018-03-08 00:19:28
【问题描述】:
问题:
你可以在共享相同视图的不同控制器中使用 ControllerAs 语法吗?
ie: (var vm = this)?
困境
我正在尝试消除控制台中由 EsLinter 生成的 linter 错误:
"Designated alias 'vm' is not assigned to 'this' consistent-this"
我想知道如何在控制器中使用:var vm = this 或将 Controller 设置为 vm(我都尝试过,但没有不工作)
唯一有效的是控制器内的 $scope(如下所示)......每当我尝试将 controller as syntax > 在 controller.js 或 html div 中,并将相关变量 (vm) 应用于 modal.html 中的插值表达式,数据不会呈现。
对此的最佳做法是什么?
** 旁注: 我在将 ng-click 动作函数 绑定到基于控制器的视图时也遇到了问题......下面的示例不起作用(对于动作)——如果我更改 {{: :action}} 到 {{::action()}} 函数在加载时触发,而不是在点击时触发:
modal.html 示例:
<article>
<h1>{{::title}}</h1>
<p>{{::body}}</p>
<button ng-click="{{::action}}">{{::button}}</button>
</article>
HTML 拉入上方 ^
<div class="hide"
ng-controller="ConfirmModalController"
ng-include src="'/app/widgets/modals/modal.html'"></div>
<div class="hide"
ng-controller="ErrorModalController"
ng-include src="'/app/widgets/modals/modal.html'"></div>
示例控制器
错误控制器
angular
.module('common.modal')
.controller('ErrorModalController', ErrorModalController);
function ErrorModalController(modalService, $scope) {
var vm = $scope;
vm.title = 'There was an error with your request';
vm.body = 'Please contact adminstrator regarding this error';
vm.button = 'Dismiss';
vm.action = function () {
console.log("closing modals");
modalService.closeAllModals();
};
}
确认控制器
angular
.module('common.modal')
.controller('ConfirmModalController', ConfirmModalController);
function ConfirmModalController(modalService, $scope) {
var vm = $scope;
vm.title = 'Confirm Your Subscription';
vm.body = '$8.99 per month will be billed to your account.';
vm.button = 'Subscribe';
vm.action = function () {
console.log("confirming subscription");
modalService.confirmSubscription();
};
}
【问题讨论】:
-
模板不是动态的,将其设为 2 个指令而不是使用 ng-include 会更有意义。
-
行得通!谢谢!
标签: angularjs scope controller angularjs-controlleras