Can't load own service into angularjs-script - javascript

So I want to inlcude a own service to a angular-script.
But it won't find the servicename, when I put it into the params of my script.
I got this script(script.js):
(function(){
var app = angular.module("Viewer", []);
var MainCtrl = function($scope, viewthis, $http, $interval, $log){
Magic;
};
app.controller("MainController", MainCtrl);
}());
And this is my service(viewthis.js):
(function()
{
var viewthis = function($http)
{
Methods, Magic;
//there is this return in a method:
return $http.get("https://api.github.com/users/" + username);
return
{
method: method
};
};
var module = angular.module("Viewer");
module.factory("viewthis", viewthis);
}());
This is the HTML head:
<head>
<script src="angular.js"></script>
<link href="style.css" rel="stylesheet" />
<script src="script.js"></script>
<script src="viewthis.js"></script>
</head>
The FireFox-Developement-tool says this in the console:
"Error: [$injector:unpr] http://errors.angularjs.org/1.2.26/$injector/unpr?p0=githubProvider%20%3C-%20github
C/<#file:///Z:/AngularTut/angular.js:6:443
gc/l.$injector<#file:///Z:/AngularTut/angular.js:36:196
c#file:///Z:/AngularTut/angular.js:34:300
gc/p.$injector<#file:///Z:/AngularTut/angular.js:36:266
c#file:///Z:/AngularTut/angular.js:34:300
d#file:///Z:/AngularTut/angular.js:35:1
f/<.instantiate#file:///Z:/AngularTut/angular.js:35:163
Pd/this.$get</<#file:///Z:/AngularTut/angular.js:67:415
N/<#file:///Z:/AngularTut/angular.js:54:23
r#file:///Z:/AngularTut/angular.js:7:369
N#file:///Z:/AngularTut/angular.js:53:393
g#file:///Z:/AngularTut/angular.js:47:256
g#file:///Z:/AngularTut/angular.js:47:256
z/<#file:///Z:/AngularTut/angular.js:46:374
fc/c/</<#file:///Z:/AngularTut/angular.js:18:310
Zd/this.$get</k.prototype.$eval#file:///Z:/AngularTut/angular.js:112:57
Zd/this.$get</k.prototype.$apply#file:///Z:/AngularTut/angular.js:112:341
fc/c/<#file:///Z:/AngularTut/angular.js:18:268
d#file:///Z:/AngularTut/angular.js:35:27
fc/c#file:///Z:/AngularTut/angular.js:18:248
fc#file:///Z:/AngularTut/angular.js:18:380
Xc#file:///Z:/AngularTut/angular.js:17:422
#file:///Z:/AngularTut/angular.js:215:30
a#file:///Z:/AngularTut/angular.js:145:67
oe/c/<#file:///Z:/AngularTut/angular.js:31:223
r#file:///Z:/AngularTut/angular.js:7:288
oe /c#file:///Z:/AngularTut/angular.js:31:207
"
If i delete "viewthis" from the params, it will build the page. With "viewthis" in it, not.
And if its easy to solve, I am sorry. I am a newbie in javascript...

Related

How to create factory in AngularJS?

I had created a factory in angular but i am getting the following error
Unknown provider:
Here is the factory:
app.factory("getFoo", function($scope){
return {
getCommi: function(val,id){
var array = ["hello","world"];
return array;
}
}
});
The controller is:
app.controller('myCtrl', ['$scope','getFoo',function($scope,getFoo){
$scope.myArr = getFoo.getCommi(4,1);
}])
What can I have to do for fix this? I just don't see any problem.
no need of scope and your factory injection should be like below
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, getFoo) {
$scope.myArr = getFoo.getCommi(4,1);
});
app.factory('getFoo', function () {
return {
getCommi: function(val,id){
var array = ["hello","world"];
return array;
}
}
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.2.x" src="https://code.angularjs.org/1.2.28/angular.js" data-semver="1.2.28"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>{{myArr}}!</p>
</body>
</html>
you just need to remove $scope from factory.
working fiddle link
Please remove $scope from the factory.
var app = angular.module('myApp',[]);
app.factory("getFoo", function(){
return {
getCommi: function(val,id){
var array = ["hello","world"];
return array;
}
}
});
app.controller('myCtrl', ['$scope','getFoo',function($scope,getFoo){
$scope.myArr = getFoo.getCommi(4,1);
}])
Remove $scope from your factory and add factory "getFoo" as a dependency in your app's run module like this:
app.run(['$rootScope', '$location', 'getFoo', function($rootScope, $location, getFoo) {
}]);

Angular not compiling correcty

I'm trying to get my head around learning $compile but just looking for a couple of pointers as to where I'm going wrong...
var app = angular.module("App", []);
app.controller("Ctrl", function ($scope, $http, $compile) {
}).directive('myDir', function ($compile) {
$(document).on("click", "#button", function ($compile) {
var newDirective = angular.element('<li>{{app data}}</li>');
$(".grid ul").append(newDirective);
$compile(newDirective)($scope);
});
});
I suppose firstly, nothing seems to work when I put it into my directory but it does when I put it in the controller. And secondly it doesn't seem to compile as the Angular tags/elements don't render correctly. I just can't figure out where I'm going wrong...
As per the Docs $compille
Compiles an HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together.
You are on the right track to use it , just need some modification in your directive code like this.
var app = angular.module("App", []);
app.controller("Ctrl", function ($scope, $http, $compile) {
}).directive('myDir', function ($compile) {
return{
restrict: 'A',
scope: {
data:"=appdata"
},
link: function(scope,element){
var newDirective = angular.element('<li>'+ scope.data +'</li>');
var content = $compile(newDirective)(scope);
element.append(content);
}
}
});
<!DOCTYPE html>
<html ng-app="App">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
<script src="app.js"></script>
</head>
<body ng-controller="Ctrl">
<div class="grid" >
Hello
<ul my-dir appdata="'whatever'">
</ul>
</div>
</body>
</html>
Plunker : https://plnkr.co/edit/xqgnhXnVoYOsXFhPMbOY?p=preview
Your directive is not formatted (created) correct. No need to use JQUERY... you are compiling the html and the data ($scope) but you are not applying the compiled template to your html.
Check this plunkr: https://plnkr.co/edit/eKdIEhyLBViWAOzfWhhV?p=preview
angular.module('plunker', [])
.directive('compileDir', ['$rootScope', '$compile', compileDir])
.controller('HomeController', [HomeController]);
function compileDir($rootScope, $compile) {
var self = {};
self.restrict = 'A';
self.scope = {
compileDirOptions: '='
};
self.link = linkFn;
return self;
function linkFn($scope, $element, $attributes) {
// I am making a new scope because I do not want to mess the directive's one, you do not have to
var newScope = angular.merge($rootScope.$new(), $scope.compileDirOptions.data);
var el = $compile($scope.compileDirOptions.html)(newScope);
$element.append(el);
}
}
function HomeController() {
var self = this;
self.message = "Hello World!";
self.data = {
html: '<li>{{name}}</li><li>{{color}}</li>',
data: {
name: 'app data',
color: 'red'
}
}
}
Your html is like this:
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.5.x" src="https://code.angularjs.org/1.5.8/angular.js" data-semver="1.5.8"></script>
<script src="app.js"></script>
</head>
<body ng-controller="HomeController as home">
<ul compile-dir compile-dir-options="home.data"></ul>
</body>
</html>

How to send value in JavaScript variable to a Angular js variable

I am having a problem sending a value of JavaScript variable to Angular js variable. I want to send a value in dataArray variable in JavaScript to Angular js variable $scope.test
html code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="angular.js"></script>
<script type='text/javascript'>
$(document).ready(function () {
// $("#fileUpload").load('test.csv');
$.get("test.csv", function(data) {
alert(data);
var rows = data.split("\r\n");
if(rows.length>0){
alert("inside if");
var firstRowCells = GetCSVCells(rows[0], ",");
var dataArray = new Array();
for(var i=1;i<rows.length;i++)
{
var cells = GetCSVCells(rows[i], ",");
var obj = {};
for(var j=0;j<cells.length;j++)
{
obj[firstRowCells[j]] = cells[j];
}
dataArray.push(obj);
}
$("#dvCSV").html('');
alert(dataArray);
$("#dvCSV").append(JSON.stringify(dataArray));
var myjson=JSON.stringify(dataArray);
//alert(myjson);
}
});
function GetCSVCells(row, separator){
return row.split(separator);
}
});
</script>
</head>
<body>
<div id="container">
Test
</div>
<div ng-app="sortApp" ng-controller="mainController">
<div id="dvCSV" ng-model="dataf" ng-bind="bdc">dfsgdfd</div>
</div>
<script src="app.js"></script>
</body>
</html>
app.js:
angular.module('sortApp', [])
.controller('mainController', function($scope) {
window.alert("Angular");
window.alert("asdfad"+$scope.bdc);
$scope.test=$scope.dataf;
window.alert($scope.myjson);
window.alert("test"+$scope.test.value);
You can do this all jquery stuff in angular using http service of angular js.
For simple http service you can refer this link -
http://www.w3schools.com/angular/angular_http.asp
I agree with previous answer. Also its wrong to use $(document).ready along with using angular framework in you application.
Try something like this:
angular.module('sortApp', [])
.service('loadTestCsv' ['$http', function($http) {
return $http.get('test.csv').then(data => {
// do all data processing you need
return data;
});
}]);
.controller('mainController', ['$scope', 'loadTestCsv', function($scope, loadTestCsv) {
loadTestCsv().then(data => {
$scope.data = data;
});
}]);

ReferenceError: random is not defined at Scope.$scope.generateRandom angular js

For some reason it gives me the error:
ReferenceError: random is not defined at Scope.$scope.generateRandom
I dont know what im doing wrong, you can go check out the website im using to do this HERE.
index.html:
<!DOCTYPE html>
<html lang= "en">
<head>
<meta charset="UTF-8" />
<title>Basic Login Form</title>
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.8/angular.js" data-semver="1.4.8"></script>
<script src = "https://rawgit.com/nirus/Angular-Route-Injector/master/dist/routeInjector.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular-route.js"></script>
<script type="text/javascript" src="script23.js"></script>
</head>
<body ng-app = "app" ng-controller = "app">
<button ng-click = "generateRandom()">Generate Random Number</button>
<br> {{randomNumber}}
</body>
</html>
script23.js:
var app = angular.module('app', []);
app.service('random', function(){
var randomNum = Math.floor(Math.random()*10)
this.generate = function(){
return randomNum;
}
});
app.controller('app' , function($scope){
$scope.generateRandom = function(){
alert("Something")
$scope.randomNumber = random.generate();
}
})
To use service in controller, you need to inject it.
app.controller('app', function ($scope, random) {
I'd recommend you to use following syntax:
app.controller('app', ['$scope', 'random', function ($scope, random) {
See Why we Inject our dependencies two times in angularjs?
Change your controller like this, since you are using the service 'random'
myApp.controller('app', ['$scope','random', function( $scope,random)
{
$scope.generateRandom = function(){
alert("Something")
$scope.randomNumber = random.generate();
}
}])
Here is the working Application

What am I doing thats causing Unknown Provider when Adding both a service and a filter or multiple services

This is most likely due to my lack of experience and overlooking something fundamental but between SO, the angulajs tutorials and guide as well as Googling and I can't find an explaination or example that I can follow.
I have successfully created a factory and used it in my controller and a filter but Only one or the other. when I try to add both to the module I get Error: Unknown provider: memberFactoryProvider <- memberFactory
my code is below but some questions I have include:
1. When adding the factory and service (or multiple factories/filters) to a module is it enough to create them the same way as you with a single factory i.e.
if I have a number of factories delclared like so:
'use strict';
angular.module('testApp', [])
.factory('factory1', function () {
var obj = {};
obj.text = "This is a test";
return obj;
});
angular.module('testApp', [])
.factory('factory2', function () {
var obj = {};
obj.text = "This is another test";
return obj;
});
is it enough to inlcude the two in app.js using angular.module('testApp', ['factory1', 'factory2']);
2. I have noticed some posts online that when creating a filter/factory they append the appname e.g.:
angular.module('testApp', [])
.factory('testApp.factory1', function () {
var obj = {};
obj.text = "This is a test";
return obj;});
is this required or personal preference?
Finally below is all my code, as mentioned above, all work indiviually but when I try to combine them I get the error mentioned above, any advice or help is greatly appreciated
index.html
<!DOCTYPE html>
<html data-ng-app="testApp">
<head>
<title>prototype</title>
<script type="text/javascript" src="jquery-2.0.3.min.js"></script>
</head>
<body>
<div data-ng-controller="myController">
<br/>
<div data-ng-repeat="n in [] | range:5">
<div data-ng-repeat="">{{test}}</div>
</div>
</div>
<br/>
<br/>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="js/app.js"></script>
<script type="text/javascript" src="js/services.js"></script>
<script type="text/javascript" src="js/filters.js"></script>
<script type="text/javascript" src="js/controllers.js"></script>
</body>
</html>
App.js
'use strict';
angular.module('testApp', ['memberFactory', 'range']);
services.js
'use strict';
angular.module('testApp',[])
.factory('memberFactory', function(){
var obj = {};
obj.text = "This is a test";
return obj;
});
filters.js
'use strict';
angular.module('testApp',[]).filter('testApp.range', function() {
return function(input, total) {
total = parseInt(total);
for (var i=0; i<total; i++)
input.push(i);
return input;
};
});
controllers.js
function myController($scope, memberFactory){
$scope.test= memberFactory.text;
}
First of all you should be doing this
angular.module('testApp', [])
.factory('factory1', function () {
var obj = {};
obj.text = "This is a test";
return obj;
})
.factory('factory2', function () {
var obj = {};
obj.text = "This is another test";
return obj;
});
You shouldn't create 2 modules of the same name.
And I think that this
angular.module('something', ['here', 'is', 'for modules', 'only'];
I think what you are trying to do is this.
You have 2 modules?
var helpers = angular.module('helpers', []);
Then you should do
var app = angular.module('app', ['helpers']);
Then you will have access to all factories that are attached to helpers and app
Say for example you want your filters in another file there are a few ways to do it
var filters = angular.module('filters', []);
filters.filter('name', func...);
Then you include it in your app like so
var app = angular.module('app', ['helpers', 'filters']);

Categories