我是 angularJS 的新手,我正在尝试编写一些可重用的代码。 当然,我阅读了文档并看到 this tutorial .
想法: 用于实例化弹出窗口的指令 D1 仅管理其内容的指令 D2 我希望 D2 指令将她的错误发送到 D1 指令。
问题: 在指令 D2 中,popupController 为空(Object {})。
除了当我尝试访问这个 Controller 时,一切都有效,这就是为什么我只在相关部分删除代码。
我的弹出指令:
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'
};
});
她的 Controller :
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);
}
};
});
内容指令:
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
...
};
});
内容 Controller :
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 内部,您只将函数添加到 $scope,而不是 Controller 本身。在 popupController 中更改为以下内容:
this.manageError = $scope.manageError = function(message) {
if ($scope.hasNotifier())
{
$scope.resetContext();
$scope.errorMessage = message;
$scope.errorDomElement.slideDown(200).delay(10000).slideUp(200);
}
};
关于javascript - 指令到指令通信: controller empty ( ={ } )- AngularJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22375368/