creating a ydn-db service for angularjs - angularjs

I'm working on a project using Meanjs and ydn-db for indexeddb support.
So I'm trying to make a service in angular, but I just can't figure a way to include the js file properly. I've tried installing the lib in the following methods:
bower install ydn-db
bower install ydndb
The first case, I could not find a suitable.js file like ydn.db-isw-core-qry-dev.js. Now the second would install the two minified versions which I could work, but I always get the ydn not found error
Now by looking into the Developer's page http://dev.yathit.com/ydn-db/getting-started.html I can see that he has a way of making the require in the AMD loader section, which I simply did not know how to use inside the service factory.
Here is what I'm trying to do inside the factory which by the way I don't think is best practices...
And these are the error that I'm getting just by trying to load this...
How can I use this lib while still following best practices for angular or at least just to get it working without errors?
ldb undefined
Object {db: Object, debug: Object}
Uncaught ydn.error.ArgumentException: Unknown attribute "keypath"
angular.module(ApplicationConfiguration.applicationModuleName).factory('Localdb',['$resource','$q',
function($resource,$q) {
var deferred=$q.defer();
require.config({
baseUrl: '/content',
paths: {
ydn: 'scripts/ydn.db-isw-core-qry-dev'
}
});
require(['scripts/ydn.db-isw-core-qry-dev'], function(ldb){
console.log ('ldb',ldb);//this is undefined
var schema ={
stores:[
{
name:'process',
keypath:'_id',
indexes:[{
name:'processId',
keypath:'processId',
unique:false
},{
name:'processMeta',
keypath:'processMeta',
unique:false
}
]
}
]
};
console.log(ydn);//this gets back ok but then the keypath error???
deferred.resolve(new ydn.db.Storage('pdc',schema));
});
return deferred.promise;
}
]);

Sorry, to get your trouble. ydn-db repo do not have compiled js file, as require (I think) by bower. So it doesn't work. Just download one of the js file and add to your html.
Also check out ydn-db with angular example app.

Related

Unable to Inject $httpBackend

I am using Angular 1.5 to write mocked services for my project by following this little example: https://embed.plnkr.co/qsmx8RUmQlXKkeXny7Rx/
This is a simple code that I have written so far:
function() {
'use strict';
angular.module('agMock', ['ag', 'ngMockE2E'])
.run(function($httpBackend) {
$httpBackend.whenGET('https://localhost:8080/api/users')
.respond({user: 'fooBarBaz', roles: ['admin', 'user']});
});
})();
'ag' is the parent module of my project for which I am going to write mocks. When I try and run this, I get the error saying 'unknown provider: $httpBackend' although I have included angular.mocks library. Can anybody take a guess what can go wrong?
So I figured out why was I getting this error. The project in which I was getting this error uses gulp to inject dependencies and generate index.html files for dev and mocked environment. In the template index.html file, I had the main parent module, "äg" referenced in the ng-app.
I skipped the part where I had to substitute "agMock" instead of "ag" in the ng-app while generating mocked index. So this was the problem. Phew.

Injecting angularFileUpload not working

this sound like a simple question but i am a newbie with angular, basicly i want to use AngularFileUpload to upload images on my website, so i did this when i initialize my app:
var app = angular.module('myApp',['ui.router'],['angularFileUpload']);
before i installed the angularFileUpload module trough npm, so my module is inside node_modules, but i get an error evertyme i start my app
error:
Failled to instantiate module due to:
'fn' is not a function, got string.
someone know what is happening?
That happens because you are injecting the modules in a wrong way.
You are inserting two arrays:
var app = angular.module('myApp',['ui.router'],['angularFileUpload']);
Instead you should insert just one array with all modules:
var app = angular.module('myApp',['ui.router','angularFileUpload']);
You should use bower instead of npm for loading your client side dependencies in AngularJs. There are following steps required to correctly load your module:
Download using following bower command
bower install angular-file-upload
Then include this library in the script tag, by providing correct location to minified js.
Last inject modules in correct way
var app = angular.module('myApp',['ui.router','angularFileUpload']);
And that's it. Please let me know if it helped you!

How to keep Grunt dom_munger from stripping your CDN dependencies?

I have an object, Plaid, that is provided by a drop-in module from Plaid, called Plaid Link. Locally, the code works perfectly in my AngularJS front-end.
The module is loaded via my AngularJS app's index.html file, right next to all of the other script tags loaded for my application.
Index.html
<script src="https://cdn.plaid.com/link/stable/link-initialize.js"></script>
Here is the code where Plaid is called: (from an AngularJS controller)
$scope.addAccount = function(bankChosen) {
$log.debug("Plaid object: ", Plaid);
var linkHandler = Plaid.create({ // the troublesome line
env: 'tartan',
clientName: 'Example Project',
key: 'test_key',
product: 'connect',
onSuccess: function(public_token) {
Restangular.one('plaid').customPOST(
{
public_token: public_token,
user_id: $scope.currentUser.id,
institution_code: bankChosen
},
'addAccount'
);
},
onExit: function() {
$state.go('dashboard.successState');
},
});
linkHandler.open(bankChosen);
};
However, when I push to the production environment, currently hosted on Heroku, it gives the javascript error ReferenceError: Plaid is not defined when it tries to load. It is breaking error when deployed to production.
What could be causing this module to be unavailable during production?
The script that loads the CDN could be getting stripped away by a standard grunt task that does that sort of thing? Or maybe I am supposed to be loading the module from the CDN in some other way in a production-environment setting? I really don't know...
Update: I found one thing that might be stripping the loaded module
From the Grunt dom-munger docs
Use this task to read and transform your HTML documents. Typical use cases include:
Read the references from your script or link tags and pass those to
concat,uglify, etc automatically.
2. Update HTML to remove script
references or anything that is not intended for your production
builds.
Add, update, or remove any DOM elements for any reason.
dom_munger is part of my application's build process, which happens when it is deployed (!). Grunt is the likely culprit here.
Does anybody know how to load the script tag above, with dom_munger as still part of my app's grunt build step?
The problem was that during the build step Grunt strips away the script tags in my application. So I had to append the tag back on to my body tag using dom_munger's update --> options --> append option.
...only then could I get the CDN script to be linked to properly after the app was built using grunt build.
The line looks like this in my Gruntfile.
--> The key added line is this one
{selector:'body',html:'<script src="https://cdn.plaid.com/link/stable/link-initialize.js"></script>'},
dom_munger:{
[.....]
update: {
options: {
append: [
{selector:'body',html:'<script src="https://cdn.plaid.com/link/stable/link-initialize.js"></script>'},
]
},
src:'index.html',
dest: 'dist/index.html'
}
Quite the mysterious error for me. I hope this helps somebody else out at some point!

Backbone.Marionette - Grunt Browserify - "require is not defined"

I'm using grunt-browserify and running into two issues in particular. The task is up and running successfully with the following config options. The variable jsFilesToConcat represents all of the javascript files for a Backbone.js + Marionette.js application, the main application defintion, the front-end utility assets (e.g. Bootstrap plugins), and all JS associated with the project. Is this the wrong approach? The thought was to load the entire 250k JS application (and all it's dependencies) at one time.
I want to offer the disclaimer that this is new territory for me, so I think my intended use case is available with the options already available with the plugin, but I'm confused by two errors:
1) Backbone not defined - which means that the script is in fact loading, however, when I inspect the call stack in Chrome Dev Tools it shows only the anonymous self-invoking function. So I'm not clear on how to pass the Backbone object to Marionette in order for it to be extended at load time.
2) require is not defined - error on the line where I'm declaring var SampleApp = require('SampleApp'). Do I need to do something special within my grunt config, or node.js server.js config to expose the require function?
3) Is the javascript executing asynchronously within itself, is this part of the browserify intended behavior that I'm not properly handling? I think since I'm wrapping alot of JS utilities in a global wrapper to protect namespacing, that's the reason some functions are not available, but I'm not clear on why that would affect require.
// uses grunt-browserify task
browserify: {
developmentJs: {
options: {
debug: true,
alias: ["./js/app.dev.js:SampleApp"],
},
src: [
'<%= pkg.jsFilesToConcat %>'
],
dest: 'public-dev/js/app.dev.js'
}
}
and then in the index.html of my single-page Marionette app, I have.
(function ($) {
$(document).ready( function() {
var sampleApp = require('SampleApp');
console.log( SampleApp );
});
})(jQuery);
Well for starters, the src attribute in your grunt file doesn't need to reference all of the files in your application. It only needs an entry point. So normally I have something similar to your anonymous self executing function in an index.js file, and set my src configuration option to ["./index.js"]. When browserify looks at that file, it will check for calls to require and grab all of the required dependencies.
That said, browserify will generate a file with an internal definition of require. The require function is not globally available on the page, nor are the dependencies that you include with require. You can use them in your application, but that doesn't make them available in the page. So if you are getting a Backbone is not defined error, the first thing I would check is that you have installed backbone via npm (npm install backbone --save).
Once everything is set up you should just have to include your compiled script on the page, and let your anonymous self executing function (which should now be in a file that grunt-browserify is processing) do the work to kick off your application.

Loading mocks into an AngularJS unit test

I'm trying to setup my AngularJS application to test out controllers, routes, templates and so on, but I'm having an issue getting some of the helper methods provided by the angular-mocks.js to work (namely module and inject).
I'm using testacular to load up the test suite with the following files added before the specs:
files = [
MOCHA,
MOCHA_ADAPTER,
'../application/lib/angular.min.js',
'./lib/angular/angular-mocks.js',
'./lib/angular/angular-scenario.js',
'../application/application.js',
'./lib/chai.js',
'./lib/chai-should.js',
'./lib/chai-expect.js',
'./spec/**/*.js'
];
So far so good, but when I run the tests I get this issue:
ReferenceError: Can't find variable: module
Not sure where this is loaded. Am I missing something?
First thing to check is that all those files are getting loaded in the test browser. It's surprisingly easy to get a path wrong in your config and not realize it. If you're running testacular with autowatch, you can navigate to http://localhost:9876/context.html with a browser and use developer tools inspect elements/resources/network and see if anything is missing.
If everything is good there and you're still having problems, post some of your test code and I'll take a look.
UPDATE: It appears (strangely) from the comments in the source for angular-mocks.js (line 1635) that window.module is only available with Jasmine. It looks like you're using Mocha instead of Jasmine. This is very likely the culprit.
ANSWER:
I can't rightly take credit for this Matsko, since you figured it out yourself... but it turns out that the current AngularJS stable download and angular-seed contain an older version of ngMock that doesn't support Mocha. Manually replacing the mock file with the latest from the github repo solves the problem. Glad I could help ;-)
I ran into this issue today and I wanted to provide others with a complete summary of the required steps to get this working. First let's say you have a module named myApp. Inside that that module there is a service called myModel. the myModel service has a method named getItems().
Currently, the angular-mocks.js (I am using AngularJS 1.0.6) does not support Mocha. You will need to visit this link and replace the 1.0.6 version with the one in the master branch from the AngularJS GitHub project. An easy way to do this (if you have wget) is wget https://raw.github.com/angular/angular.js/master/src/ngMock/angular-mocks.js in the correct directory. If you use a properly configured Sublime or vim it can also easily pull it down for you.
Make sure your karma.conf.js file includes the angular-mocks.js file in files array
Somewhere in your tests.js file (maybe at the top level describe) include beforeEach(module('myApp')); or whatever you named your main module.
If you plan to use the service (or whatever you want to include in the test) in more than one place you can call another beforeEach where needed like this:
beforeEach(inject(function(myModel) {
mymodel = myModel;
}));
otherwise you just can inject where it is needed. Now the mymodel variable (notice this is the variable you assigned in the beforeEach above) will be available to you for testing in your next blocks. For example, you can now write:
describe('when fetched', function() {
it('should return 3 items', function() {
// console.log(mymodel.getItems());
expect(mymodel.getItems()).to.have.length(3);
});
});

Resources