AngularJS: Browser ignores my Controller Definition (Dependency Injection) - javascript

I am using angular-translate in my project but I am unable to define a controller that has a dependency injection of $translate. The code isn't executed in the browser. I checked JSHint already...
index.html
<html ng-app='ngApp'>
<body>
<div ng-controller="orderFormCtr">
<ul>
<li>{{'TITLE' | translate}}</li>
<li translate="TITLE"></li>
</ul>
</div>
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-translate/angular-translate.js"></script>
<script src="app.js"></script>
</body>
</html>
app.js
angular.module('ngApp', ['pascalprecht.translate']);
// this code works
angular.module('ngApp').config(['$translateProvider', function ($translateProvider) {
$translateProvider.translations('en', {
TITLE: 'Hello'
});
$translateProvider.translations('de', {
TITLE: 'Hallo'
});
}]);
// the browser ignores this code
angular.module('ngApp').controller('orderFormCtr', ['$scope', '$translate', function ($scope, $translate) {
alert("Controller Code executed");
}]);

var app = angular.module('ngApp', ['pascalprecht.translate']);
// this code works
app.config(['$translateProvider', function ($translateProvider) {
$translateProvider.translations('en', {
TITLE: 'Hello'
});
$translateProvider.translations('de', {
TITLE: 'Hallo'
});
$translateProvider.preferredLanguage('en');
//or translateProvider.determinePreferredLanguage()
}]);
// the browser ignores this code
app.controller('orderFormCtr', ['$scope', '$translate', function ($scope, $translate) {
alert("Controller Code executed");
}]);
http://jsbin.com/miqazola/1/

Related

"Unknown Provider" error when using Angular ui-router when using service in controller

I am trying to use a Service (rates service) in my Controller (rates controller) and get an "Error: Unknown Provider". Does anyone have any suggestions on how to fix this? Cheers!
rates.contoller.js
(function () {
'use strict';
angular.module('print.module').controller('ratesCtrl', ['$http', '$scope', '$rootScope', 'ratesService', function ($http, $scope, $rootScope, ratesService) {
ratesService.getRatesDataService();
}]
)})();
rates.service.js
(function () {
'use strict';
angular.module('print.module').service('ratesService', ['$scope', '$http', function ($scope, $http) {
vm = this;
function getRatesDataService() {
console.log("test");
return this.$http.get("api/Rates/GetRates");
}
//}
}]
)
})();
print.module.js
(function () {
"use strict";
var module = angular.module('print.module', [
'ui.router',
]);
module.config(function ($stateProvider, $urlRouterProvider, $locationProvider) {
$urlRouterProvider.otherwise('/print');
$stateProvider
.state('print', {
url: '/print',
templateUrl: "Public/scripts/sharedViews/printNavbar.html"
})
.state('print.rates', {
url: "/rates",
controller: 'ratesCtrl',
templateUrl: "Public/scripts/rates/rates.view.html",
controllerAs: 'vm'
})
$locationProvider.html5Mode(true);
});
}());
view (scripts tags only for reference)
<body ng-app="print.module">
<div ui-view></div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.3.1/angular-ui-router.min.js"></script>
<script type="text/javascript" src="~/public/scripts/print.module.js"></script>
<script type="text/javascript" src="~/public/scripts/books/books.controller.js"></script>
<script type="text/javascript" src="~/public/scripts/terms/terms.controller.js"></script>
<script type="text/javascript" src="~/public/scripts/rates/rates.service.js"></script>
<script type="text/javascript" src="~/public/scripts/rates/rates.controller.js"></script>
<script type="text/javascript" src="~/public/scripts/services/modals.service.js"></script>
</body>
You can't use $scope inside Service

cannot pass parameters via angular service between 2 html file

I have 2 html file and I want to pass parameters via angular service between them.
these are the files I have:
index.html
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body>
<script type="text/javascript" src="services.js"></script>
<div ng-app="myApp" ng-controller="myCtrl2">
</div>
enter here
<script>
var app=angular.module("myApp");
app.controller("myCtrl2", ['$scope','$location', 'myService',
function($scope, $location, myService) {
myService.set("world");
}]);
</script>
</body>
</html>
enter2.html
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body>
<script type="text/javascript" src="services.js"></script>
<div ng-app="myApp" ng-controller="myCtrl3">
hello {{x}}
</div><script type="text/javascript">
var app=angular.module("myApp");
app.controller("myCtrl3", ['$scope','$location', 'myService',
function($scope, $location, myService) {
$scope.x=myService.get();
}]);
</script>
</body>
</html>
services.js
var app=angular.module("myApp", []);
app.factory('myService', function() {
var savedData = {}
function set(data) {
savedData = data;
}
function get() {
return savedData;
}
return {
set: set,
get: get
}
});
why can't I get "hello world" in enter2.html, but instead get "hello" (x is not found by service)...?
When you go from index.html to enter2.html the whole page loads from scratch. For the data that you are expecting to stay in the browser, you might need to use advanced angular concepts such as loading just a part of the page using ng-view.
If that's something you have already overruled, saving the data in the service somewhere (may be the browser session) before unloading (window.onunload event) the page and then loading it back from there when the service loads (window.onload event) could also work.
Here is a working example based on your code.
I kept your index.html and added ui-view to have a single page application. The app uses 'ui.router'.
In the myCtrl2 I saved the data in the service, and call it back from myCtrl3:
.controller('myCtrl2', ['$scope', 'myService', function($scope, myService) {
console.log('myCtrl2');
myService.set('world');
}])
.controller('myCtrl3', ['myService', function(myService) {
console.log('myCtrl3');
var vm = this;
vm.x = myService.get();
}])
To keep things simple, I have one Javascript file:
angular.module('myApp', ['ui.router'])
.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/home');
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'index.html',
controller: 'myCtrl2',
controllerAs: 'vm'
})
.state('enter2', {
url: '/enter2',
templateUrl: 'enter2.html',
controller: 'myCtrl3',
controllerAs: 'vm'
});
})
.factory('myService', function() {
var savedData = {}
function set(data) {
savedData = data;
}
function get() {
return savedData;
}
return {
set: set,
get: get
}
})
.controller('myCtrl2', ['$scope', 'myService', function($scope, myService) {
console.log('myCtrl2');
myService.set('world');
}])
.controller('myCtrl3', ['myService', function(myService) {
console.log('myCtrl3');
var vm = this;
vm.x = myService.get();
}])
I also uses the var vm=this and ControllerAs as often recommended to avoid $scope issues.
index.html looks like below... pleaes note the ui-sref instead of href:
<div ui-view="">
<a ui-sref="enter2">Enter here</a>
</div>
enter2.html is now just the div part and your content:
<div>
Hello {{ vm.x }}
</div>
Let us know if that helps.
Additional info:
AngularJS Routing Using UI-Router
AngularJS's Controller As and the vm Variable
Sounds like you need to use a controller for your view page
https://docs.angularjs.org/guide/controller

Problems with uploading a file and parsing with AngularJS

Trying to build a simple application that allows a user to upload a file, and upon clicking the 'add' button, It parses the file and displays the result within the browser.
I am using IntelliJ to generate the AngularJS application stub, and modifying it accordingly.
My attempt is below:
view1.html
<!DOCTYPE html>
<html lang="en" ng-app>
<head>
<meta charset="utf-8">
<title>My HTML File</title>
<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css">
<link rel="stylesheet" href="../app.css">
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/ng-file-upload/ng-file-upload-shim.js"></script> <!-- for no html5 browsers support -->
<script src="bower_components/ng-file-upload/ng-file-upload.js"></script>
<!--<script src="view1.js"></script>-->
</head>
<body>
<div ng-controller="View1Ctrl">
<input type="file" id="file" name="file"/>
<br/>
<button ng-click="add()">Add</button>
<p>{{data}}</p>
</div>
</body>
</html>
view1.js
'use strict';
angular.module('myApp.view1', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view1', {
templateUrl: 'view1/view1.html',
controller: 'View1Ctrl'
});
}])
.controller('View1Ctrl', ['$scope', function ($scope) {
$scope.data = 'none';
$scope.add = function() {
var f = document.getElementById('file').files[0],
r = new FileReader();
r.onloadend = function(e) {
$scope.data = e.target.result;
}
r.readAsArrayBuffer(f);
}
}]);
view1_test.js
'use strict';
describe('myApp.view1 module', function() {
beforeEach(module('myApp.view1'));
describe('view1 controller', function(){
it('should ....', inject(function($controller, $rootScope) {
//spec body
// var view1Ctrl = $controller('View1Ctrl');
var $scope = $rootScope.$new(),
ctrl = $controller('View1Ctrl', {
$scope: $scope
// $User: {}
});
expect(ctrl).toBeDefined();
}));
});
});
app.js
'use strict';
// Declare app level module which depends on views, and components
angular.module('myApp', [
'ngRoute',
'myApp.view1',
'myApp.view2',
'myApp.version'
]).
config(['$routeProvider', function($routeProvider) {
$routeProvider.otherwise({redirectTo: '/view1'});
}]);
I am not sure where I could potentially be going wrong? I viewed quite a few questions to this and tried multiple different approaches but I cannot get this to work despite all of my tests passing.
The issue was around my view1.js file. I found the Papa Parse library extremely useful.
Here is my solution used from the open source Papa Parse community:
Papa.parse(fileInput[0], {
complete: function(results) {
console.log("Complete!", results.data);
$.each(results.data, function(i, el) {
var row = $("<tr/>");
row.append($("<td/>").text(i));
$.each(el, function(j, cell) {
if (cell !== "")
row.append($("<td/>").text(cell));
});
$("#results tbody").append(row);
});
}
});

Angular.js controller that uses multiple services

I can't seem to figure how to inject multiple services into a controller.
I have listed my files here:
index.html file:
<script src="'./angular/angular.min.js'></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-beta.2/angular-sanitize.js"></script>
<script src="'./angular-route/angular-route.js'></script>
<script src='./app/app.js'></script>
<script src='./app/welcome/welcome.js'></script>
<script src='./app/controls/questions.js'></script>
<script src='./app/services/questionsdata.js'></script>
<script src='./app/services/getsong.js'></script>
console.log error:
Error: [$injector:unpr] http://errors.angularjs.org/1.5.0/$injector/unpr?p0=getsongProvider%20%3C-%20getsong%20%3C-%20QuestionsCtrl
at Error (native)
at http://localhost:8000/static/angular/angular.min.js:6:416
at http://localhost:8000/static/angular/angular.min.js:43:7
at Object.d [as get] (http://localhost:8000/static/angular/angular.min.js:40:270)
at http://localhost:8000/static/angular/angular.min.js:43:69
at d (http://localhost:8000/static/angular/angular.min.js:40:270)
at e (http://localhost:8000/static/angular/angular.min.js:41:1)
at Object.instantiate (http://localhost:8000/static/angular/angular.min.js:41:364)
at http://localhost:8000/static/angular/angular.min.js:87:42
at link (http://localhost:8000/static/angular-route/angular-route.js:977:26) <section class="container-fluid ng-scope" id="main" ng-view="">
My app.js file:
(function(){
'use strict';
angular.module('myApp', ['ngRoute', 'myApp.welcome', 'myApp.questions' ])
.config(function ($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
redirectTo: '/welcome'
})
.when('/welcome', {
templateUrl: 'static/app/welcome/welcome.html',
controller: 'WelcomeCtrl'
})
.when('/questions', {
//templateUrl: 'static/app/questions/questions.html',
templateUrl: 'static/app/views/questions.html',
//controllerAs: 'question',
controller: 'QuestionsCtrl'
})
.otherwise('/')
});
})();
My controller file:
(function () {
'use strict';
angular
.module('myApp.questions', ['ngRoute', 'ngSanitize'])
.controller('QuestionsCtrl', QuestionCtrl);
function QuestionCtrl(questionsdata,getsong) {
var vm = this;
var data = {
params: "1,1"
};
....
My questionsdata (first service) file:
(function () {
'use strict';
angular
.module('myApp.questions')
.factory('questionsdata', questionsdata);
function questionsdata() {
var service = {
getQuestions: getQuestions
};
return service;
.....
My get song (second service) file
(function () {
'use strict';
angular
.module('myApp.questions')
.factory('getsong',getsong);
function getsong($http, $window, $interval) {
var service = {
getId: getId,
getMySong: getMySong
};
return service;
....
That's ain't working.
When I change my controller file to use only the questionsdata service as follows:
'use strict';
angular
.module('myApp.questions', ['ngRoute', 'ngSanitize'])
.controller('QuestionsCtrl', QuestionCtrl);
function QuestionCtrl(questionsdata) {
It's working well. But when trying to use only the get song service as follows:
'use strict';
angular
.module('myApp.questions', ['ngRoute', 'ngSanitize'])
.controller('QuestionsCtrl', QuestionCtrl);
function QuestionCtrl(getsong) {
It ain't working as well.
Weird, right? What am I missing?
Try using the inject method:
'use strict';
angular
.module('myApp.questions', ['ngRoute', 'ngSanitize'])
.controller('QuestionsCtrl', QuestionCtrl);
QuestionCtrl.$inject = ['getsong', 'questiondata'];
function QuestionCtrl(getsong, questiondata){
Try this in index.html:
<script src="'./angular/angular.min.js'></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-beta.2/angular-sanitize.js"></script>
<script src="'./angular-route/angular-route.js'></script>
<script src='./app/controls/questions.js'></script>
<script src='./app/welcome/welcome.js'></script>
<script src='./app/app.js'></script>
<script src='./app/services/getsong.js'></script>
<script src='./app/services/questionsdata.js'></script>
Because myApp depends on myApp.welcome and myApp.questions, so you have to put them first.

End-to-End Testing AngularJS app with Jasmine

I have an AngularJS app. I would like to implement some end-to-end testing that I can run on-demand. In an effort to do this, I've built a basic test screen with the following:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test Results</title>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jasmine/2.0.0/jasmine.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jasmine/2.0.0/jasmine-html.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jasmine/2.0.0/boot.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular-mocks.js"></script>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/jasmine/2.0.0/jasmine.css" />
<!-- Load the Test Files-->
<script type="text/javascript" src="e2e/tests.e2e.js"></script>
</head>
<body>
run tests
</body>
</html>
My tests.e2e.js file looks like the following:
'use strict';
describe('MyApp', function() {
browser.get('http://localhost:11000/index.html');
describe('Welcome Screen', function () {
});
});
When click "run tests" in my test runner, I get an error that says:
MyApp encountered a declaration exception
ReferenceError: browser is not defined
My question is, what am I doing wrong? The examples I've seen use browser to basically start the app. However, I can't seem to figure out how to do end-to-end tests on-demand.
Thank you for any help you can provide.
(function (module) {
var myController = function ($scope, $http) {
$http.get("/api/myData")
.then(function (result) {
$scope.data= result.data;
});
};
module.controller("MyController",
["$scope", "$http", myController]);
}(angular.module("myApp")));
describe("myApp", function () {
beforeEach(module('myApp'));
describe("MyController", function () {
var scope, httpBackend;
beforeEach(inject(function ($rootScope, $controller, $httpBackend, $http) {
scope = $rootScope.$new();
httpBackend = $httpBackend;
httpBackend.when("GET", "/api/myData").respond([{}, {}, {}]);
$controller('MyController', {
$scope: scope,
$http: $http
});
}));
it("should have 3 row", function () {
httpBackend.flush();
expect(scope.data.length).toBe(3);
});
});
});

Categories