Service injection into controller having in seperate files with AngularJS - angularjs

When i try to inject service into controller which I have in separate file mentioned in below code i get error:
TypeError: myService.getData is not a function
at new (controllers.js:18)
at Object.e [as invoke] (angular.min.js:39)
at M.instance (angular.min.js:80)
at D (angular.min.js:61)
at g (angular.min.js:55)
at g (angular.min.js:55)
at angular.min.js:54
at angular.min.js:20
at r.$eval (angular.min.js:133)
at r.$apply (angular.min.js:134)
index.html
load all js files in this html page
<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>title</title>
<link rel="stylesheet" href="styles/all.css">
<script src="libs/angular.min.js"></script>
<script src="libs/jquery.js"></script>
<script src="js/service.js"></script>
<script src="js/controllers.js"></script>
<script src="js/myApp.js"></script>
<script src="libs/bootstrap/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
</body>
</html>
This is the main file where we load controllers and services at once
myApp.js
var app = angular.module('app', ['app.service', 'app.controllers']);
service.js
here i tried to get data from server and wants to use in controller
var app = angular.module("app.service", []);
app.service('myService', function($http) {
function getData (callbackFunc) {
$http({
method: 'GET',
url: "url"
}).success(function(data){
callbackFunc(data);
}).error(function(){
alert("error");
});
}
});
controllers.js
This file include all logic and inject myService from service.js file.
i use myService from service.js and tried to get data, but i got an error all the time
angular.module('app.controllers', ['app.service'])
.controller('myCtrl', ['$scope', '$http', '$timeout', 'myService',
function ($scope, $http, $timeout, myService) {
myService.getData(function(dataResponse) {
$scope.surveys = dataResponse;
});
}]);

Your service module declaration has problem.
You are getting module name without declaring it.
Try like this
var appSvc=angular.module("app.service",[]);
appSvc.service('myService', function($http){});
bind Your method with this
Like this
this.getData =function (callbackFunc) {}

Related

Angular Controller is not triggering

My controller is not triggering. It should be stupid but I can't see why.
Here find my code structure.
Please help me find that basic error.
template :
<!DOCTYPE html>
<html ng-app="attachmentsApp" ng-cloak="">
<head>
<meta charset="utf-8"/>
<script th:inline="javascript">
/*<![CDATA[*/
var source = [[${source}]];
var appContext = /*[[#{/}]]*/ '';
/*]]>*/
</script>
</head>
<body>
<div th:replace="include"></div>
<script th:src="#{/app/modules/attachments/scripts/attachmentsapp.js}"></script>
<script th:src="#{/app/modules/attachments/scripts/controllers/AttachmentsHomeCtrl.js}"></script>
<script th:src="#{/app/modules/attachments/scripts/services/AttachmentsHomeService.js}"></script>
</body>
</html>
App :
angular
.module('attachmentsApp', ['ngRoute'
]).run(['$rootScope', function($rootScope){
$rootScope.appContext = window.appContext;
$rootScope.language = window.language;
$rootScope.source = window.source;
}])
.config(function($routeProvider) {
$routeProvider.when('/', { templateUrl: window.appContext + 'app/modules/attachments/views/home.html', controller: "AttachmentsHomeCtrl" })
});
Controller:
angular.module('attachmentsApp').controller('AttachmentsHomeCtrl', ['$scope','$rootScope','AttachmentsHomeService','$window',
function ($scope,$rootScope,AttachmentsHomeService,$window) {
console.log($rootScope.source);
debugger;
}]);
Service :
'use strict';
angular.module('attachmentsApp').service('AttachmentsService', [ '$http', '$rootScope', function($http, $rootScope){
this.getForm = function(type) {
debugger;
}
return this;
}]);
Many thanks
Suggesting some change in your HTML:
1) Define and load files before their use: ng-app was being used before attachmentsapp.js file is loaded in DOM
2) Order of usage: service file was loaded after its usage in controller
It should be look like:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<script th:inline="javascript">
/*<![CDATA[*/
var source = [[${source}]];
var appContext = /*[[#{/}]]*/ '';
/*]]>*/
</script>
<script th:src="#{/app/modules/attachments/scripts/attachmentsapp.js}"></script>
<script th:src="#{/app/modules/attachments/scripts/services/AttachmentsHomeService.js}"></script>
<script th:src="#{/app/modules/attachments/scripts/controllers/AttachmentsHomeCtrl.js}"></script>
</head>
<body ng-app="attachmentsApp" ng-cloak="">
<div th:replace="include"></div>
</body>
</html>
Not 100% sure, but it should be working. Do a try !!
Moreover, keep an eye on console.
It was the Service name.
AttachmentsHomeService as registering it in Controller
AttachmentsService in service definition
Many thanks for your help

data to read my json file in IONIC

This world is sad to cry , am blocked for two hours with a problem that i couldnt define ,i can't retrieve data from my json file ,everything in my code seems correct.
This is my factory:
'use strict';
angular.module('starter.services')
.factory('userService',function ($http) {
return{
getUsers:function(){
return $http.get("http://localhost:26309/api/User/getAll/").then(function (response) {
return response.data;
});
}
}
});
and this controller :
'use strict';
angular.module('starter.controllers', ['starter.services'])
.controller('UsersCtrl', function($scope,userService) {
$scope.Users = [];
userService.getUsers().then(function (data) { $scope.Users= data.data; }); });
});
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
<link href="css/ionic.app.css" rel="stylesheet">
-->
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="lib/ionic/js/angular/angular-resource.min.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="cordova.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
<script src="js/UserControllerIonic.js"></script>
<script src="js/UsersServiceIonic.js"></script>
</head>
<body ng-app="starter" ng-controller="UsersCtrl">
<ion-view>
<div class = "list" >
<a class = "item" ng-repeat = "user in Users">
<h2>{{user.nom}}</h2>
</a>
</div>
</ion-view>
</body>
</html>
Thank you in advance
SOLUTION
i solved the problem by :
1- adding in the config.xml the permission <allow-navigation href="http://*/*"/>
2-installing cordova-plugin-whitelist ionic plugin add cordova-plugin-whitelist
3-add control-allow-origin extention to chrome :https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi/related?hl=en-US
and finally : specifying the type of data returned by the back-end controller by adding this code to my Global.asax in Application_start method :config.Formatters.JsonFormatter.SerializerSettings.Formatting =
Newtonsoft.Json.Formatting.Indented;
config.Formatters.Remove(config.Formatters.XmlFormatter);
hope this helps someone
You don't want to resolve your $http call inside factory.
JS:
angular.module('app',[])
.controller('MainCtrl', function($scope, MyService){
var url = "http://jsonplaceholder.typicode.com/users";
MyService.getData(url).then(function(res){
console.log(res.data);
$scope.data = res.data;
});
})
.service('MyService', function($http){
return {
getData: function(url){
return $http.get(url);
}
}
})
HTML:
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="MainCtrl">
<ul>
<li ng-repeat="item in data">{{item.name}}</li>
</ul>
</body>
</html>
The issue is that you are resolving the promise in service with the value response.data, and again expecting the resolved value to have data property. Change your service code as below:
'use strict';
angular
.module('starter.services')
.factory('userService',function ($http) {
return {
getUsers: function(){
return $http.get("http://localhost:26309/api/User/getAll/").then(function (response) {
return response;
});
}
}
});
Or simply return the promise as below:
'use strict';
angular
.module('starter.services')
.factory('userService',function ($http) {
return {
getUsers: function(){
return $http.get("http://localhost:26309/api/User/getAll/");
}
}
});

Angular JS Unit Testing using Jasmine

I have a factory service as below
FamilyService.js
(function(){
'use strict';
angular.module('app')
.factory('ABC', FamilyService);
FamilyService.$inject = ['DEF'];
function FamilyService(DEF) {
function returnTrue() {
var a="true";
}
}
}());
I want to call returnTrue method in My test case
**TestFamilyService.js**
describe('testing my_controller.my_function', function () {
var mockedFactory, $rootScope, $controller;
beforeEach(module('app', function($provide) {
mockedFactory = {
save: jasmine.createSpy()
};
$provide.value('ABC', mockedFactory);
}));
it('should call the save function', function() {
expect(mockedFactory.returnTrue()).toHaveBeenCalled();
});
});
**specrunner.html**
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Jasmine Spec Runner v2.4.1</title>
<link rel="shortcut icon" type="image/png" href="lib/jasmine-2.4.1/jasmine_favicon.png">
<link rel="stylesheet" href="lib/jasmine-2.4.1/jasmine.css">
<script src="lib/jasmine-2.4.1/jasmine.js"></script>
<script src="lib/jasmine-2.4.1/jasmine-html.js"></script>
<script src="lib/jasmine-2.4.1/boot.js"></script>
<script src="lib/jasmine-2.4.1/angular.js"></script>
<script src="lib/jasmine-2.4.1/angular-mocks.js"></script>
<!-- include source files here... -->
<script src="src/Player.js"></script>
<script src="src/webapp/Mock.js"></script>
<script src="src/webapp/FamilyService.js"></script>
<!-- include spec files here... -->
<script src="spec/TestFamilyService.js"></script>
</head>
<body>
</body>
</html>
When i run specrunner.html in the browser it displays
Error: No module: app
TypeError: Unable to get value of the property 'returnTrue': object is null or undefined
Please Tel me whats wrong here?
In FamilyService.js
angular.module('app').factory('ABC', FamilyService);
you are creating a factory for the existing module app, but if the module doesn't exist you need to write
angular.module('app',[]).factory('ABC', FamilyService);
In your case just create a new file, where the angular module gets created
angular.module('app',[]);
UPDATE
Just include the dependencies of your module in the html
<script src="lib/angular-sanititze/angular-sanitize.js"></script>
If you want to mock these modules, you can do something like
beforeEach(function() {
angular.module('second',[]);
}
But in the case that you are using some methods of the third party library, you need to mock these methods as well.

How to update controller variable with 'ng-model' AngularJS?

I am trying to get user input through a text box using ng-model, and append to a base URL for a http.get call as follow;
index.html:
<html ng-app='vidRoute'>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Search Video</title>
<link rel="stylesheet" href="app/css/custom/main.css">
<link rel="stylesheet" href="app/css/custom/responsive.css">
</head>
<body>
<div id='mainwrapper'>
<div id='header' ng-controller="searchController">
<input type="text" id="searchTxt" ng-model="append">
Search Video
</div>
<div id="poster">
<div ng-view></div>
</div>
</div>
<script type="text/javascript" src="app/javascript/vendor/jquery-2.1.1.js"></script>
<script type="text/javascript" src="app/javascript/vendor/angular.js"></script>
<script type="text/javascript" src="app/javascript/vendor/angular-route.js"></script>
<script type="text/javascript" src="app/javascript/vendor/angular-resource.js"></script>
<script type="text/javascript" src="app/javascript/vendor/angular-mocks.js"></script>
<script type="text/javascript" src="app/javascript/custom/searchcontroller.js"></script>
<script type="text/javascript" src="app/javascript/custom/vidRoute.js"></script>
</body>
</html>
searchcontroller.js
'use strict';
var vidcontrol = angular.module("vidcontrol", []);
vidcontrol.controller("vidcontroller", ['$scope', '$http', function($scope, $http) {
$http.get('http://api.themoviedb.org/3/tv/airing_today?api_key=d5e87524383e2872a9555990b268dc5b').success(function(response) {
$scope.results = response.results;
});
}]);
vidcontrol.controller('searchController', ['$scope', '$http',
function ($scope, $http) {
var url = "http://api.themoviedb.org/3/search/movie?api_key=d5e87524383e2872a9555990b268dc5b&query=";
// var searchTxt = $('#searchTxt').val();// this works fine when used
var searchUrl = url + append; //$scope.append also logs 'undefined' on the console
$http.get(searchUrl).success(function (response) {
$scope.searchResults = response.results;
});
}]);
but I'm not getting any response. when I log searchUrl on console, I could see that append was not updated according to value from text box. I'm quite new to Angular and I can't figure out what I'm doing wrong. What should I do to fix this?
Now, I see the issue. When controller loaded, it executes controller code. That mean REST query runs before view is built. That is reason you see undefined problem. Solution is to define a method in controller which will be invoked when you click "Search Video".
Update view
Search Video //Look at ng-click
Update Controller:
vidcontrol.controller('searchController', ['$scope', '$http',function($scope, $http) {
var url = "http://api.themoviedb.org/3/search/movie?api_key=d5e87524383e2872a9555990b268dc5b&query=";
$scope.search = function(){ // Look at here, Defined a method to invoke on "Search Video" link click
var searchUrl = url + $scope.append;
$http.get(searchUrl).success(function(response) {
$scope.searchResults = response.results;
});
};
} ]);

AngularJS Argument '***' is not a function, got undefined

I am using the Ionic framework to build an hybrid app with AngularJS and Cordova. Completely new to both AngularJS and JavaScript, this has not been a sweet ride.
Everything was working fine until I decided to re-organize the structure of my app with 1 file per controller/service. So I'm pretty sure that the problem is coming from there, I just can't find how to fix it.
Here's the code:
js/app.js
angular.module('app', ['ionic', 'app.controllers'])
.run(function($ionicPlatform) {
...
})
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('login', {
url: '/login',
templateUrl: 'templates/login.html',
controller: 'LoginCtrl'
})
...
js/controllers/LoginCtrl.js
angular.module('app.controllers', [])
.controller('LoginCtrl', ['$scope', '$http', '$state'], function($scope, $http, $state) {});
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="cordova.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers/LoginCtrl.js"></script>
</head>
<body ng-app="app">
<ion-nav-view></ion-nav-view>
</body>
</html>
Tried many variations of the code above, to no avail.
Any help greatly appreciated...
Edit
I might have made some progress in finding out what the problem is (or just yet another symptom).
In my index.html file, if I switch the order of declaration of the controllers, the one declared right after app.js always gets ignored. This is the error I get when I put them in the order below
Controller 'ionNavBar', required by directive 'ionNavButtons', can't be found!
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="cordova.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers/RegisterCtrl.js"></script>
<script src="js/controllers/LoginCtrl.js"></script>
the function of your controller has to be inside the dependencies array.
.controller('LoginCtrl', ['$scope', '$http', '$state', function($scope, $http, $state) {}]);
And i think you also have to inject $ionicPlatform in your run() and config function, like this
.run(["$ionicPlatform", function($ionicPlatform) {
...
}])
.config(["dep1", function(dep1) {}]);

Resources