【发布时间】:2017-06-20 19:59:31
【问题描述】:
我对 AngularJS 控制器的“as”语法有疑问。我正在尝试使用 bootstrap nanomodals 并将控制器 $scope 附加到它们。
现在,我为我的模态创建了角度组件。我也在 html 中创建我的对话框。
我的html代码:
<body ng-app="application">
<div ng-controller="accountController as $acc" class="controller-account">
<script type="text/ng-template" id="loginModal.html">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Nowe konto</h4>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="userNameInput">Nazwa użytkownika:</label>
<input type="text" class="form-control" id="userNameInput" placeholder="Wprowadź nazwę użytkownika">
</div>
<div class="form-group">
<label for="userPasswordInput">Hasło:</label>
<input type="password" class="form-control" id="userPasswordInput" placeholder="Password">
</div>
<div class="form-group">
<label for="userEmailInput">E-Mail:</label>
<input type="email" class="form-control" id="userEmailInput" placeholder="Wprowadź E-mail">
</div>
<button ng-click="$acc.okButton()" class="btn btn-primary">Załóż konto</button>
</form>
</div>
</script>
我的 JS 脚本:
var angularApp = angular.module('application', ['ngAnimate', 'ngSanitize', 'ngCookies', 'ui.bootstrap']);
angularApp.component('loginModalComponent', {
templateUrl: 'loginModal.html',
bindings: {
resolve: '<',
close: '&',
dismiss: '&'
},
controller: () => {
var $acc = this;
$acc.$onInit = () => {
};
$acc.okButton = () => {
console.log('Liiiii');
//HTTP request about login
};
$acc.closeButton = () => {
$acc.close();
}
}
});
angularApp.controller('accountController', ['$scope', '$http', '$cookies', '$uibModal',
function($scope, $http, $cookies, $uibModal){
var $acc = this;
$acc.isUserSignIn = false;
$acc.loginModalOpen = () => {
var modalInstance = $uibModal.open({
animation: true,
component: 'loginModalComponent',
resolve: {
}
});
};
}]);
我不知道为什么,但我不能在这个例子中使用 $acc.okButton() 函数。
【问题讨论】:
-
HTML 代码是否应该是组件本身的代码,还是您正在尝试使用那里的组件?
-
我想在 [link]plnkr.co/edit/mKrqmV35ary96rItbw6N?p=preview 中做同样的事情,但我不得不错过一些东西。这个 html 是我的主页视图。在脚本标签中的 ng-controller 中,我得到了由组件使用的模态模板。单击某个按钮后出现对话框,但我无法调用任何 $acc 函数。
-
这并不能真正回答我的任何问题,但基本上,不要将控制器与组件混合使用。该组件已经指定了它的控制器。您需要将模板拆分为自己的 html 页面,然后只需将控制器包含在您想要的
页面中。组件基本上是简化的指令。
标签: javascript angularjs angular-ui-bootstrap