0
我是新来的angularJS,我试图做一些可重用的代码。 我当然看了文档,看到了this tutorial。指令通信的指令:控制器为空(= {}) - AngularJS
的想法: 一项指令D1实例化一个弹出 一个指令D2只管理它的内容 我想D2指令给她的错误发送到D1指令。
问题: 在指令D2,所述popupController是空的(对象{})。
Everyting工作除了当我尝试访问该控制器,这就是为什么我切的代码只对有关的部分。
我popupDirective:
app.directive('popup', function($compile){
return {
restrict: 'E',
scope: {
show: '=',
title: "@popupTitle",
notifier: "@notifier"
},
controller: 'popupController',
replace: false,
transclude: true,
link: function(scope, element, attrs) {
scope.dialogStyle = {};
if (attrs.width)
scope.dialogStyle.width = attrs.width;
if (attrs.height)
scope.dialogStyle.height = attrs.height;
scope.hideModal = function() {
scope.show = false;
};
},
templateUrl: 'Popup.html'
};
});
她的控制器:
app.controller('popupController', function($scope) {
$scope.errorMessage = "";
$scope.modalShown = false;
$scope.toggleModal = function() {
$scope.modalShown = !$scope.modalShown;
};
$scope.hideModal = function() {
$scope.show = false;
};
$scope.hasNotifier = function()
{
return $scope.notifier;
};
$scope.manageError = function(message) {
if ($scope.hasNotifier())
{
$scope.resetContext();
$scope.errorMessage = message;
$scope.errorDomElement.slideDown(200).delay(10000).slideUp(200);
}
};
});
的contentDirective:
app.directive('contentDialog', function($compile) {
return {
restrict: 'E',
scope: {},
// Search for the controller on the paren element
require: '^popup',
controller: 'ContentController',
replace: true, // Replace with the template below
link: function(scope, element, attrs, popupController) {
...
scope.popupCtrl = popupController;
console.log(popupController);
popupController.manageError("salut");
// HERE THE POPUPCONTROLLER IS EMPTY
...
};
});
内容控制器:
app.controller('ContentController', ['$scope', 'ContentRs', function($scope, UseCase) {
...
$scope.updateContent = function()
{
if($scope.selectedContent.id !== -1)
{
var description = $scope.getSelectedContentDescription();
ContentRs.update({
id: $scope.selectedContent.id,
name: $scope.selectedContent.name,
description: description
}, function(){
// on sucess
$scope.resetContext();
}, function(){
// on failure
$scope.popupCtrl.manageError("Update failed.");
// HERE THE POPUPCONTROLLER IS EMPTY
});
}
else
{
console.log("Error");
}
};
}]);
编辑,我忘了HTML: 主HTML:
<popup popup-title="Use case management" notifier="true" show='modalShown'
width='330px' height='450px'>
<content-dialog show='modalShown'></content-dialog>
</popup>
谢谢:)
嗨,谢谢你的回答。我不明白。如果我像这样注入popupController,我将无法使用我的contentController吗?也许我错过了一些东西:/ – ogdabou
对不起,我对两个控制器感到困惑。 是的你是对的,你不能使用它 - 但我问自己,如果第二个控制器实际上甚至是有用的,或不能移动链接功能内的逻辑? 为指令设置控制器的唯一真正原因是如果您希望多个指令相互通信。在popup-Controller中会出现这种情况,而不是在contentController中 - 或者我错过了什么? – Charminbear
@Charminbar 其实你解决了我的问题!我不得不使用this.manageError而不是$ scope.managerError。如果我只是改变我的弹出窗口运行良好!谢谢:) – ogdabou