I have a ng-controller in _Layout page like this.
<div ng-controller="LayoutController">
left content....
#RenderBody
right content..
And using angular module in layout with ajax ( that part works )
<script type="text/javascript">
var module_ = angular.module("myapp", []);
var controller_ = module_.controller("layoutController", function ($scope) {
$.ajax({
type: "POST",
url: "Home/GetMenu",
success: function (result) {
$.each(result, function (i, ix) {
result[i].ID = i + 1;
});
$scope.TopCharactersModel = result;
$scope.$apply();
},
complete: function () {
}
})
Then i want to use another Ng-Controller inside Index.html which derived from this layout page.
Javascript code is not work at this side and chrome debugger show this error
WARNING: Tried to load angular more than once.
<div ng-controller="IndexController">
<div class="panel-group" id="accordion" ng-repeat="arr_ in newsArr">
</div>
</div>
<script>
var module = angular.module("myapp", []);
var myController1 = module_.controller("IndexController", function ($scope) {
$.ajax({
url: "Home/GetNews",
type: "POST",
success: function (result) {
$scope.newsArr = result;
// $scope.$digest();
$scope.$apply()
},
complete: function () {
}
});
});
</script>
For second controller try this.
<script>
var module = angular.module("myapp", []);
var myController1 = module.controller("IndexController", function ($scope) {
$.ajax({
url: "Home/GetNews",
type: "POST",
success: function (result) {
$scope.newsArr = result;
// $scope.$digest();
$scope.$apply()
},
complete: function () {
}
});
});
</script>
Assuming you are within the same app and you're not creating some sort of hybrid application with multiple spa's... you are in fact redeclaring the module: myapp. If you need a reference to the myapp module remove the [] from angular.module("myapp", []);
Creation versus Retrieval Beware that using angular.module('myModule',
[]) will create the module myModule and overwrite any existing module
named myModule. Use angular.module('myModule') to retrieve an existing
module.
Pasted from module documentation.
Related
I am trying to do a file upload using angularjs. But I am getting this error for the past few days and I am unable to resolve:
angular.js:13920 Error: [$injector:unpr] http://errors.angularjs.org/1.5.8/$injector/unpr?p0=fileUploadServiceProvider%20%3C-%20fileUploadService%20%3C-%20appCtrl
at angular.js:38
at angular.js:4511
at Object.d [as get] (angular.js:4664)
at angular.js:4516
at d (angular.js:4664)
at e (angular.js:4688)
at Object.invoke (angular.js:4710)
at S.instance (angular.js:10354)
at p (angular.js:9263)
at g (angular.js:8620)
I only want to read the files uploaded, and store it in the server, and not to link to other URL. I am using Django for my backend. This are my codes:
HTML
<body ng-app="myApp">
<div ng-controller="appCtrl">
<input type="file" id="file" name="files" accept="text/*"
data-url="file" class="upload" ng-model="uploadFile"/>
<label for="file">
<span class="glyphicon glyphicon-open" id="selectFile">
</span>Select a file
</label>
</div>
</body>
<script src="../static/js/services/fileUploadService.js"></script>
<script src="../static/js/controllers/fileUploadController.js"></script>
<script src="../static/js/fileModel.js"></script>
Directives:
var app = angular.module('myApp', [])
app.directive("filesInput", function() {
return {
require: "ngModel",
link: function postLink(scope,elem,attrs,ngModel) {
elem.on("change", function(e) {
var files = elem[0].files;
ngModel.$setViewValue(files);
})
}
}
});
Service
var app = angular.module('myApp', [])
app.factory('fileUploadService', function ($rootScope) {
var _files = [];
var service = {
add: add,
clear: clear,
upload: upload,
}
return service
function add(file){
_files.push(file)
$rootScope.$broadcast('fileAdded', file.files[0].name)
}
function clear(){
_files = []
}
function upload(){
_files.submit();
}
Controller:
var app = angular.module('myApp', [])
app.controller('appCtrl', function ($scope, $rootScope, $http, fileUploadService){
$scope.$watch('uploadFile', function (newVal, oldVal) {
var submitBtn = document.getElementById('submitBtn');
//clear existing files
fileUploadService.clear()
if(newVal == true){
var formdata = new FormData();
$scope.getTheFiles = function ($files) {
angular.forEach($files, function (value, key) {
formdata.append(key, value);
});
};
// NOW UPLOAD THE FILES.
$scope.uploadFile = function () {
var request = {
method: 'POST',
url: file,
data: formdata,
headers: {
'Content-Type': undefined
}
};
// SEND THE FILES.
$http(request)
.success(function (d) {
alert(d);
})
.error(function () {
});
}
}]);
fileUploadService.add(newVal)
fileUploadService.upload()
}
})
By using this:
var app = angular.module('myApp', [])
it creates a new module, so controller, service and directive are registered in a separate module! This results in the injection error as controller cannot inject the service, as it is registered in a different module.
The solution is to only create one module and register all the other components in it, like this:
1st file:
var app = angular.module('myApp', []);
angular.module('myApp').factory('fileUploadService', function ($rootScope) {
...
});
2nd file
angular.module('myApp').controller('appCtrl', function ($scope, $rootScope, $http, fileUploadService){
...
});
3rd file:
angular.module('myApp').directive("filesInput", function() {
...
});
Avoid multiple statements that create the module.
ERRONEOUS
var app = angular.module('myApp', [])
app.directive("filesInput", function() {
//...
});
var app = angular.module('myApp', [])
app.factory('fileUploadService', function ($rootScope) {
//...
}};
var app = angular.module('myApp', [])
app.controller('appCtrl', function ($scope, $rootScope, $http, fileUploadService){
//...
});
The extra angular.module('myApp', []) statements are overwriting existing modules, resulting in the fileUploadService becoming unregistered.
BETTER
angular.module('myApp', [])
angular.module('myApp').directive("filesInput", function() {
//...
});
angular.module('myApp').factory('fileUploadService', function ($rootScope) {
//...
}};
angular.module('myApp').controller('appCtrl', function ($scope, $rootScope, $http, fileUploadService){
//...
});
The statement creating the module must be placed before all the code adding more entities to it.
From the Docs:
Creation versus Retrieval
Beware that using angular.module('myModule', []) will create the module myModule and overwrite any existing module named myModule. Use angular.module('myModule') to retrieve an existing module.
For more information, see
AngularJS Developer Guide - Modules - Creation versus Retrieval
AngularJS angular.module Function API Reference
I have a server set up on localhost:5000 that has a JSON string that contains "Hello world"
I want my AngularJS application to fetch this data, and display it.
here is what I have.
this is the script getJSON.js
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http({
method : "GET",
url : "localhost:5000"
}).then(function mySuccess(response) {
$scope.myWelcome = response.data;
}, function myError(response) {
$scope.myWelcome = response.statusText;
});
});
this is how I call it in my html
<div ng-app="myApp" ng-controller="myCtrl">
<p>Today's welcome message is:</p>
<h1>{{myWelcome}}</h1>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("localhost:5000")
.then(function(response) {
$scope.myWelcome = response.data;
});
});
</script>
now the "myWelcome" should be "Hello world" but it just displays myWelcome when I run the code.
the backend is fully working! I've done it with regular Angular but need it to work with AngularJS unfortunately.
Any advice?
This is not a full answer I see what you're trying to do. It looks like you're not calling the correct controller and your value never gets updated. Move your app definition into your script tags and remove the controller that you have there
//index.html
<script>
var app = angular.module('myApp', []);
</script>
// myCtrl.js
app.controller('myCtrl', function($scope, $http) {
$scope.myWelcome = 'test';
$http({
method : "GET",
url : "localhost:5000"
}).then(response) {
$scope.myWelcome = response.data;
}, catch(error) {
$scope.myWelcome = error;
});
});
Next check your network tab and see if the request is actually executed. If it is not then you're controller is not connected to the app properly. You should be able to set breakpoints at this time and see what is firing and what is not.
EDIT: Also make sure you're loading your js file into your view after the first script tag is fired. Otherwise 'app' will not be defined.
I am implementing logic through ui-router, Factory and Directive but getting error: JavaScript runtime error: [$injector:modulerr] in Angular Js.
Ui-Routing was working fine.
Index.html file:
<html><head><title>Employee Management System</title>
<link href="Content/bootstrap.css" rel="stylesheet" />
<script src="Scripts/jquery-1.9.1.min.js"></script>
<script src="Scripts/angular.min.js"></script>
<script src="Scripts/angular-ui-router.min.js"></script>
<script src="Scripts/bootstrap.min.js"></script>
<script src="Scripts/app/EmpRecord.js"></script>
<script src="Scripts/app/GetDataService.js"></script>
<script src="Scripts/app/EmpController.js"></script>
<script src="Scripts/app/EmpApp.js"></script></head>
<body ng-app="EmpApp">
<div class="page-header">Employee Management System
</div><div ng-include="'pageContents/menu.html'"></div>
<ui-view></ui-view></body></html>
EmpApp.js
var app = angular.module("EmpApp", ['ui.router']);
app.factory('EmpFact', ['$http', EmpFact])
.controller('EmpController', ['$scope', 'EmpFact',EmpController])
.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
templateUrl: '/home.html'
})
.state('Add', {
templateUrl: '/AddEmployee.html'
})
.state('List', {
templateUrl: 'ListEmp.html',
controller: 'EmpController'
}
)
})
.directive('emp-Record', EmpRecord);
ListEmp.html:
<div><div><h3>List of Employees</h3></div>
<div EmpRecord ng-repeat="e in Employees"></div></div>
EmpController
<div><div><h3>List of Employees</h3></div>
<div EmpRecord ng-repeat="e in Employees"></div></div>
GetDataService.js
var EmpFact = function ($http) {
var records = {}
$http.get('http://localhost/EmployeeApi/api/Emp')
.then(function (response) {
records= response.data;
});
return {
GetData: function () {
alert(records);
return records;
}
}
}
All Errors are gone Now but data is not coming.
In short:
Controller:
var EmpController= function ($scope,EmpFact) {
$scope.Employees = EmpFact.GetData();
console.log($scope.Employees);
};
Service:
var EmpFact = function ($http) {
var records = {}
$http.get('http://localhost/EmployeeApi/api/Emp')
.then(function (response) {
records= response.data;
});
return {
GetData: function () {
alert(records);
return records;
}}}
Àpp.js
app.factory('EmpFact', ['$http', EmpFact])
.controller('EmpController', ['$scope','EmpFact', EmpController])
.directive('empRecord', function () {
return {
template: "<tr><td>{{e.empid}}</td><td>{{e.empName}}</td><td>{{e.empEmail}}</td><td>{{e.empSalary}}</td>"
}});
HTML:
<div>
<div><h3>List of Employees</h3></div>
<div emp-Record ng-repeat="e in Employees"></div>
</div>
Ok, so as I suggested in the comment, because the error implies that you haven't injected the EmpFact factory into EmpController, changing
.controller('EmpController', ['$scope', EmpController])
Into:
.controller('EmpController', ['$scope', 'EmpFact', EmpController])
And also injecting it to the controller function:
var EmpController = function ($scope, EmpFact) { ... };
Made the error disappeared, but now you say that "data is not coming".
I suggest another change in your factory, instead of your current code, try this:
var EmpFact = function ($http) {
return {
GetData: function () {
// return a promise which resolve with the actual data returned from the server
return $http.get('http://localhost/EmployeeApi/api/Emp').then(
function (response) {
// return the actual results, instead of the whole response from the server
return response.data;
}
);
}
}
};
Now, in your controller, you should be able to get the data like this:
var EmpController = function ($scope, EmpFact) {
// Call the "GetData" from the factory, which return a promise with the actual results returned from the server
EmpFact.GetData().then(
function(data) {
// in the resolve callback function, save the results data in
// any $scope property (I used "$scope.Employees" so it will be
// available in the view via {{ Employees | json }})
$scope.Employees = data;
}
);
};
By returning a promise you are guaranteed to be able to handle the results returned from an asynchronous request (AJAX). You should be able to use the results in the view like this:
<div emp-Record ng-repeat="e in Employees"></div>
(Note that the above HTML snippet is taken from the comments below this answer)
Edit:
Looking at your directive, it doesn't look like a correct way to construct a table. Change emp-Record to emp-record and wrap it in a <table> tag to make it a valid HTML:
<table>
<tr emp-record ng-repeat="e in Employees"></tr>
</table>
And in your directive's template make sure you close the row tag (Add </tr>):
.directive('empRecord', function () {
return {
template: "<tr><td>{{e.empid}}</td><td>{{e.empName}}</td><td>{{e.empEmail}}</td><td>{{e.empSalary}}</td></tr>"
}
});
Thanks Alon for your help as I am new to Angular, converting my ASP.NET MVC code to HTML5/Angular only.
Finally I am able to resolve it.
Data Service/Factory:
var EmpFact = function ($http) {
return {
GetData: function () {
return $http.get('http://localhost/EmployeeApi/api/Emp');
}
}
}
Controller:
var EmpController = function ($scope, EmpFact) {
//EmpFact.GetData() is a promise.
EmpFact.GetData().then(
function (result) {
$scope.Employees= result.data;
}
);
}
I have created a simple app to store an event to my database. It is working fine but with a wordaround.
I use the following method:
controllers.controller('CalendarAddController', function($scope, $routeParams, Event) {
$scope.addEvent = function() {
$scope.ev=new Event();
$scope.ev.title = $scope.event.title;
$scope.ev.$save().then(function(res) { console.log("success");})
.catch(function(req) { console.log("error saving obj"); })
.finally(function() { console.log("always called") });
}
});
After submitting my form, the function addEvent is called.
If I print the value of $scope.event, it has the right values.
However, when I call .$save() on it, I get the error "TypeError: $scope.event.$save is not a function."
But when I create a new object and assign the values to it, it works fine.
Why isn't it working directly? Always creating a dummy object does not seem to be best practice I suppose.
The service I created
services.factory( 'Resource', [ '$resource', function( $resource ) {
return function( url, params, methods ) {
var defaults = {
update: { method: 'put', isArray: false },
create: { method: 'post' }
};
methods = angular.extend( defaults, methods );
var resource = $resource( url, params, methods );
resource.prototype.$save = function() {
if ( !this.id ) {
return this.$create();
}
else {
return this.$update();
}
};
return resource;
};
}]);
services.factory( 'Event', [ 'Resource', function( $resource ) {
return $resource( '/api/calendar/:id' );
}]);
Update: basic example
Using this example everything works front-end but in my rest API the data is not passed.
<!DOCTYPE html>
<html lang="en-US">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-resource.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-route.min.js"></script>
<script type="text/javascript">
var app = angular.module('app', ['ngRoute','ngResource'])
.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl : 'pages/home.html',
controller : 'mainController'
})
});
app.factory('Event', function($resource) {
return $resource('/test/api/:id');
});
app.controller('mainController', ['$scope', '$routeParams', 'Event',
function($scope, $routeParams, Event) {
function handleSuccess(data) {
alert("success");
}
function handleError(data) {
alert("error");
}
var event = new Event();
event.title = "a title";
Event.save(event, handleSuccess, handleError);
}]);
</script>
<body>
<div ng-app="app">
<div ng-view></div>
</div>
</body>
</html>
For the back-end I created a very basic script which writes the request to a file:
It always says "array()" so no data is passed.
<?php
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = print_r($_REQUEST,true);
fwrite($fh, $stringData);
fclose($fh);
?>
Where do you initialize $scope.event or is it automatically created by angular? If this is an plain JavaScript object you can't call .$save, but you can use the Event service itself - no need to create a new instance:
Event.create($scope.event)
UserServices.js
angular.module('UserService', ['ngResource']).factory('UserFactory', ['$http', function() {
return {
// call to get all nerds
get : function() {
return $http.get('/api/User');
},
// call to POST and create a new geek
create : function(userData) {
return $http.post('/api/User', userData);
},
// call to DELETE a geek
delete : function(id) {
return $http.delete('/api/User/' + id);
}
}
}]);
UserCtrl.js
angular.module('UserCtrl', ['UserFactory']).controller('UserController',
['$scope','UserFactory', function($scope, UserFactory) {
$scope.insert = function(){
$scope.fromfactory = UserFactory.create($scope.user);
}
}]);
In UserCtrl, you need to retrieve the module, not redefine it:
UserCtrl
angular.module('UserService').controller('UserController'...);
Here is a proper structure of a module:
JS
var app = angular('app', ['ngResource']);
app.factory('UserFactory', function() { ... });
app.controller('UserCtrl', function($scope) {...});
HTML
<body ng-app='app'>
...
</body>