【发布时间】:2018-03-15 00:10:41
【问题描述】:
我是 AngularJS 的新手,正在尝试使用该框架重做我以前的应用程序的一些工作。我正在尝试在我的应用程序 (AngularJS v1.6.6) 中创建一个消息框服务,模块调用该服务以在 UI 中显示一个弹出窗口。
我似乎无法弄清楚如何将服务的变量绑定到 UI 本身。我尝试在控制器中创建一个本地“MessageBox”变量并引用它的内容,以及简单地调用注入的变量而没有运气。有什么方法可以通过服务来实现吗?我在考虑一个全局变量,但我看到了反对这个的建议。
服务似乎是最好的选择,但我愿意接受任何在这里更有意义的建议。其他模块需要显示自己的错误或成功消息,所以我认为创建一个标准的方法来处理它会更容易。
我的代码如下:
message-box.template.html
<div id="message" ng-show="$ctrl.MessageBox.display" style="background-color: white; border: 1px solid black; margin: 5px; float: right; top: 60px; right: 2%; padding: 5px; position: fixed; z-index: 100;">
<img id="message-image" height="30" width="30" alt="{{ $ctrl.MessageBox.Image.alt }}" ng-src="{{ $ctrl.MessageBox.Image.source }}" /> <span id="message-text">{{ $ctrl.MessageBox.text }}</span>
</div>
message-box.module.js
angular.module("components.message-box", ["components"])
.controller("MessageBoxController", ["$scope", "MessageBox", function MessageBoxController($scope, MessageBox) {
}]);
message-box.component.js
/**
* message-box.component.js
* Contains the 'message-box' component
*/
angular.module("components.message-box")
.component("messageBox", {
templateUrl: "/Scripts/cop/components/message-box/message-box.template.html",
controller: "MessageBoxController"
});
message-box.service.js
/**
* message-box.service.js
* Defines the 'message-box' service
*/
angular.module("components.message-box")
.service("MessageBox", function () {
var self = this;
self.display = false;
self.Image = {
alt: null,
source: null
};
self.text = null;
self.timeout = null;
/**
* Hides the displayed message
* @public
*/
self.hideMessage = function () {
self.display = false;
self.timeout = null;
self.Image.alt = null;
self.Image.source = null;
self.text = null;
};
/**
* Displays the provided message to the user
* @public
* @param {string} text Message text
* @param {Object} Image Image display data
* @param {number} [hideTimeoutMs=null] Number of miliseconds to wait before hiding the message
*/
self.showMessage = function (text, Image, hideTimeoutMs) {
self.text = text;
self.Image.alt = Image.alt;
self.Image.source = Image.src;
self.display = true;
// Cancel timer for current timeout if it exists
if (self.timeout !== null) {
self.timeout = null;
}
// Set a new timeout if specified
if (hideTimeoutMs !== undefined) {
self.timeout = setTimeout(self.hideMessage, hideTimeoutMs);
}
};
});
以下是尝试调用服务的示例:
visual.module.js
angular.module("core.visual", [
"ngRoute",
"core.visual.settings"
])
.controller("VisualController", ["$routeParams", "$scope", "MessageBox",
function VisualController($routeParams, $scope, MessageBox) {
var self = this;
self.MessageBox = MessageBox;
self.MessageBox.showMessage("This is a message", "/Content/Images/loading.png", "Loading", 10000);
}
]);
我也尝试过不使用 MessageBox 作为本地控制器变量,但没有成功 - 这只是我的最新尝试。
我在正确的轨道上吗?这甚至可能吗?
【问题讨论】:
标签: angularjs