问题:
您可以在共享相同视图的不同控制器中使用 ControllerAs 语法吗?
即:(var vm = this)?
困境
我试图摆脱 EsLinter 生成的控制台中的 linter 错误:
"Designated alias 'vm' is not assigned to 'this' consistent-this"
我想知道如何在控制器中使用:var vm = this或将控制器设置为 vm(我都尝试过,但它不起作用)
唯一有效的是控制器内的$scope(如下所示)......每当我尝试将控制器应用为 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();
};
}