我在我的webapp中使用Twitter Bootstrap for UI.特别是它的警报组件.我想编写一个简单的角度服务来包装Bootstrap的Alert,以便有可能通知用户任何角度代码的安静.像这样:
Informer.inform("message", "ERROR"); // will result in alerting with `alert-error` class
Informer.inform("message", "INFO"); // will result in alerting with `alert-info` class
Run Code Online (Sandbox Code Playgroud)
我的想法是将模板附加到以下结尾<body>:
<div class="alert {{alertClass}} fade in informer" id="informer">
<button type="button" class="close" data-dismiss="alert">×</button>
<div class="valignCenterWrapper">
<div class="valignCenter" id="informerMessage">
{{message}}
</div>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
像这样的东西:
grfx.factory("Informer", function() {
return {
inform : function(message, type) {
// Here be dragons. How can I compile/append the template.
$("#inform").alert();
}
};
});
Run Code Online (Sandbox Code Playgroud)
我唯一想知道的是:如何使用angular来编写它,而不是使用jQuery?上面的代码是否适合开始?互联网中的人说我应该只使用指令进行DOM操作.但我不明白:我没有任何现有的标记来应用它的指令.由于某些compupations /用户交互,警报将附加到页面.哪些服务($compile, …
我面临AngularJS,服务和范围的“问题”。
这并不是一个真正的问题(我发现了几种方法可以使它起作用),但是我想知道我是否做对了,或者我所做的事情是否会在将来导致问题
我有一个可以保存一些全局数据的服务;该服务有两种方法:getData()refreshData()
refreshData触发一些工作(其余调用等),并在不同控制器内部的精确点被调用,以响应用户操作(单击按钮等)。
(显然)调用了getData来取回数据。
在控制器中,我应该如何使用它来访问数据并将其放在作用域中,以便可以从视图中访问它?
选择1:
controller('MyController', function ($scope, myService) {
$scope.data = myService.getData();
//use data in functions and in the view, ex: ng-hide="data.forbidden"
Run Code Online (Sandbox Code Playgroud)
选择2:
controller('MyController', function ($scope, myService) {
$scope.data = function() { return myService.getData(); }
//use data() in functions and in the view, ex: ng-hide="data().forbidden"
Run Code Online (Sandbox Code Playgroud)
选择3:
controller('MyController', function ($scope, myService) {
$scope.forbidden = function() { return myService.getData().forbidden; }
//... one function for each data.member used in this view
//usage in the view: ng-hide="forbidden()"
Run Code Online (Sandbox Code Playgroud)
替代方案4:使用$ apply或$ watch
我目前正在使用第二种方法,因为即使没有创建新的控制器,它也可以工作(考虑同一页面中使用不同控制器的不同部分)。 …
我目前有一项服务,取决于$ cookies中设置的变量.但是,当我想要对服务和$ cookies中存储的值之间的交互进行单元测试时,则在实际初始化$ cookie值之前始终初始化服务.
所以,我的问题是:如何正确地测试服务和$ cookie值之间的交互?(例如:如何在我的服务初始化之前设置$ cookies中的值?)
注意:我使用Angular 1.2和Karma进行单元测试.
cookies unit-testing angularjs angularjs-service karma-runner
更新:我设法进一步缩小问题范围,并通过更新包含一些无效ascii字符的 httpBackend.when请求来修复意外请求错误.
我已经附加了一个Plunker与他当前的代码块.
但是我仍然难以有效地测试触发成功和错误方法操作.我还需要增加检查消息广播的期望.
为了测试上面提到的场景,我设计了一个我已经包含在Plunker中的hack,但我相信应该有更好的方法来测试这些场景.
任何有关如何克服此问题并测试响应消息状态的线索将非常感激.
问题
我为我的测试设置了$ httpBackend的预期值/响应,但是当我运行$ httpBackend.flush()时,它无法指示下面提到的错误.
指示错误消息
Error: Unexpected request: GET https://192.168.1.10:3334/res?t1=CHECK&t2='?'&req={"_msgType":"Login_msg","UserName":"e@e.com","Password":"123"}
Run Code Online (Sandbox Code Playgroud)
我确实找到了一些讨论这个问题域的有用链接,它们确实帮助我缩小了问题范围.但我似乎还无法弄清楚这个单元测试失败的具体原因.
有用的堆栈溢出问题
有用的外部资源
我也试过移动flush()调用,并尝试调用$ apply或$ digest,如此处所示,在测试中发出$ http请求.
要测试的AngularJS服务
app.service('restService',['$log','$http','$rootScope',function($log,$http,$rootScope)
{
this.location = null;
this.port = null;
this.sendRequest = function(host,port,param1,param2,requestMsg)
{
this.location = host;
this.port = port;
$http.get('https://'+host+":"+port+"/res?t1="+param1+"&t2="+param2+"&req="+JSON.stringify(requestMsg)).
success(function(data) {
//Need …Run Code Online (Sandbox Code Playgroud) unit-testing angularjs angularjs-service httpbackend karma-jasmine
我正在使用一个非常简单的拦截器来检查响应拒绝403 Access Forbidden将用户重定向到登录,但它没有重定向.我可以将console.log直接放到$ location.path之前和之后的行,并且它永远不会发生.这事发生在别人身上过吗?我一直在盯着这个...原来我甚至不想使用$ location,但我不能注入ui.router而没有获得循环依赖,我也无法弄清楚如何摆脱这么多的位置应该让我感动,而我想到了.
.factory('AuthInterceptor', ['$q', '$location',
function( $q, $location ) {
var service = {
responseError: function( responseRejection ) {
// Authorization issue, access forbidden
if( responseRejection.status === 403 ) {
// TODO: show a login dialog, and/or redirect to login
console.log("Response rejected. Redirecting to login...");
$location.path('/login');
$location.replace();
console.log("Not so much with the redirecting... I'm still here");
}
// Propagate error to any chained promise handlers
return $q.reject( responseRejection );
}
}
return service;
}])
Run Code Online (Sandbox Code Playgroud) 我想覆盖价值 -
angular.module("data", []).value('apiBase', '/api1/data')
Run Code Online (Sandbox Code Playgroud)
在运行时,我试图修改它 -
angular.module("data").value('apiBase', '/someotherapi/data')
Run Code Online (Sandbox Code Playgroud)
在某些服务/控制器中,但它失败了,它没有覆盖apiBase的值.
我试着注入apiBase我的控制器并进行更改.
angular.module('data').controller(function(apiBase){apiBase = '/someotherapi/data'})
Run Code Online (Sandbox Code Playgroud)
它失败了.
然后我尝试将apiBase defination更改为像这样的对象
angular.module("data", []).value('apiBase', {"api_base_url":"/api1/data"})
Run Code Online (Sandbox Code Playgroud)
然后在控制器中修改它:
angular.module('data').controller(function(apiBase){apiBase.api_base_url = '/someotherapi/data'})
Run Code Online (Sandbox Code Playgroud)
有用.所以我的问题是:为什么angular.module('data').value('samekey', 'newvalue')不能覆盖价值?当它只是一个字符串/数字(主要类型.第二次尝试)时,为什么不能修改该值.在我看来,Value提供者是单身,它应该改变.
我的服务需要异步检索一个值,但是一旦我拥有它,我想使用该值的缓存版本.
当两个控制器调用此服务时,我希望第一个控制器缓存检索到的值,第二个控制器使用缓存值,但根据日志,我从未找到缓存值.当它运行时,我看到一条日志消息,显示正在缓存的值,然后,当我按照一个角度路由到另一个控制器时,我没有看到服务找到缓存的值.为什么它没有按照我的期望运行**?**
angular.module('myApp.services').factory('Config', function() {
var Config = { };
Config.currentYear = function() {
if (Config._currentYear) {
// sadly, we never execute here
console.log("returning cached year");
return Parse.Promise.as(Config._currentYear);
}
return Parse.Config.get().then(function(config) {
console.log("caching year");
Config._currentYear = config.get("currentYear");
return Config._currentYear;
});
};
return Config;
});
Run Code Online (Sandbox Code Playgroud)
一些注意事项:(1)我将缓存的属性命名为_currentYear,添加下划线以避免与函数名冲突.不确定我是否需要这样做.(2)当缓存值时,我返回一个履行的承诺,因此函数总是返回一个promise ...也不确定是否需要它,但认为它不会受到伤害.
javascript promise angularjs parse-platform angularjs-service
在我的应用程序中,我有两个几乎相同的控制 很多功能都是一样的,所以我想把它们原型化.这是控制器#1:
c2gcontroller.js
angular.module('c2gyoApp')
.controller('C2gCtrl', function($scope) {
// some unique stuff
$scope.feeDay = 59;
...
// the identical functions
$scope.getMinutes = function(minutes) {
var duration = moment.duration(minutes, 'm');
return duration.minutes();
};
...
});
Run Code Online (Sandbox Code Playgroud)
和控制器#2:
c2gbcontroller.js
angular.module('c2gyoApp')
.controller('C2gbCtrl', function($scope) {
// some unique stuff
$scope.feeDay = 89;
...
// the identical functions
$scope.getMinutes = function(minutes) {
var duration = moment.duration(minutes, 'm');
return duration.minutes();
};
...
});
Run Code Online (Sandbox Code Playgroud)
我试过投入$scope.getMinutes工厂:
smfactory.js
angular.module('c2gyoApp')
.factory('smfactory', function() {
return {
getHours: function(minutes) {
var duration …Run Code Online (Sandbox Code Playgroud) dependency-injection angularjs angularjs-service angularjs-factory angularjs-provider
我想定义一个使用$locale服务的常量.常量是对象,因此我不能将其作为参数注入,就像控制器一样.我怎么用呢?
angular.module('app').constant('SOME_CONSTANT', {
'LOCALE': $locale.id.slice(0, 2)
})
Run Code Online (Sandbox Code Playgroud) javascript dependency-injection constants angularjs angularjs-service
我正在尝试向控制器1发送一个充满对象的数组到控制器2.但是我在控制器2中得到的只是一个空数组.我得到一个填充的唯一方法是在我的服务中创建一个静态数组.
我的服务
app.service('myData', function () {
this.myData = [];
this.addData = function(data) {
this.myData.push(data);
}
this.getData = function() {
return this.myData;
}});
Run Code Online (Sandbox Code Playgroud)
控制器1设置数据
app.controller('controller1',['$scope', 'myData', function($scope, myData) {
$scope.addData = function(index, name) {
myData.addData({index: index, name: name});
}}]);
Run Code Online (Sandbox Code Playgroud)
控制器2看起来像这样
app.controller('controller2',['$scope', 'myData', function($scope, myData) {
$scope.myData = myData.getData();
$scope.$watch('myData.getData()', function(data){
console.log(data);
});
console.log($scope.myData);}]);
Run Code Online (Sandbox Code Playgroud)
当我在寻找答案时,我发现了很多类似于我的问题.唯一的区别是我从控制器填充我的服务而不是创建静态服务.
我的console.logs都返回一个空数组.为什么是这样?
angularjs ×10
javascript ×3
unit-testing ×2
constants ×1
cookies ×1
dom ×1
httpbackend ×1
jquery ×1
karma-runner ×1
promise ×1