我正在学习 Angular,这就是为什么有时我无法理解代码。我得到了 Angular 自定义服务的代码。先看代码。
angular.module('yourModule').factory('alertService', function() {
return {
showError : function() {
$.bigBox({
title: title,
content: content == null ? "An error occurred.<br /><br />If this error persists, please contact support." : content,
color: "#C46A69",
//timeout: 6000,
icon: "fa fa-warning shake animated",
//number: "1",
timeout: 3000
});
}
};
});
然后你可以将它注入(inject)到任何 Controller 中并使用它:
angular.module('yourModule').controller('yourController', function($scope, alertService) {
someFunction().success(function (result) {
// great!
}).error(function (error) {
// call standard error message function
alertService.showError("Update Failed"); // use default error message
});
});
问题1
当注入(inject)内置服务时,我们会像这样使用 $ 符号 $scope 或 $window 等 但是当注入(inject)自定义服务时,只需写服务名称而不用 $ 符号,为什么?
如果我们需要用 $ 符号注入(inject)我自己的服务,那么会出现什么问题吗? 对于 $ 符号,我是否需要使用任何特定代码模式创建服务?
问题2
showError : function() {
}
我们可以这样声明上面的函数名吗
this.showError = function() {
};
$scope.showError = function() {
}
如果我的理解有问题,请指正。
最佳答案
问题#1 $ 符号用于 Angular 内置服务,以便您可以区分核心服务和内置服务。建议您不要将 $ 用于您自己的服务
问题 #2: 不。您正在返回一个对象, showError 是对象的键和作为值的函数。对象键总是定义为
{
showError: function (){
}
}
以下模式通常用于 Controller ,而不是服务。
this.showError = function() {
};
$scope.showError = function() {
}
关于AngularJS 自定义服务注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36434812/