Why won't my service register? - angularjs

I tried creating a service in angularjs but I keep getting angular.js:10467 Error: [ng:areq] Argument 'MainController' is not a function, got undefined.
html:
<div ng-controller="MainController">
<form name="searchUser" method="post">
<input ng-model="username" type="search" placeholder="Find"/>
<input type="submit" value="Search" ng-click="search(username)" />
</form>
You are searching for: {{username}}
<hr />
<div ng-repeat="(key,value) in data">
{{ key + " : " + value}}
</div>
</div>
<script src="lib/angular/angular.js"></script>
<script src="js/app.js"></script>
<script src="services/Screamer.js"></script>
my app.js:
angular.module('NoteTaker', []); // dependcies in array.
angular.module('NoteTaker', []).controller('MainController', function(screamer, $log, $http, $scope, $interval){
$http({
method : 'GET',
url: 'https://api.github.com/users/' + $scope.username
}).then(function(response){
console.log(response);
$scope.data = response.data;
}, function(response){
console.log(response);
});
my service in service.js
(function() {
'use strict';
angular.module('NoteTaker', []).factory('screamer', function(){
return {
say: "blahbalh"
};
});
}());

angular.module(name, dependencies) creates a new module. If you want to add to an existing one, use angular.module(name):
angular.module('NoteTaker', []); // dependcies in array.
angular.module('NoteTaker')
.controller('MainController', function(screamer, $log, $http, $scope, $interval) {
$http({
method: 'GET',
url: 'https://api.github.com/users/' + $scope.username
}).then(function(response) {
console.log(response);
$scope.data = response.data;
}, function(response) {
console.log(response);
});
});
// service.js
(function() {
'use strict';
angular.module('NoteTaker').factory('screamer', function() {
return {
say: "blahbalh"
};
});
}());
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="NoteTaker" ng-controller="MainController">
<form name="searchUser" method="post">
<input ng-model="username" type="search" placeholder="Find" />
<input type="submit" value="Search" ng-click="search(username)" />
</form>
You are searching for: {{username}}
<hr />
<div ng-repeat="(key,value) in data">
{{ key + " : " + value}}
</div>
</div>
I create a new module on line 1, and add the controller & service to it.

tcooc answered your question, but I'll try to make it a little easier to understand:
app.module('myModule', ['dep1', 'dep2']); // passing an array creates a NEW module
Access the newly created module by calling the same method, but without the array of dependencies:
app.module('myModule')
.controller('MyController')
.service('MyService')
.factory('MyFactory');
Or, just attach everything to the first module call:
app.module('myModule', ['dep1', 'dep2'])
.controller('MyController', function(...) {})
.service('MyService', function(...) {})
.factory('MyFactory', function(...) {});
Also, it helps to write dependency injection like this:
MyController.$inject = ['$scope', '$location', '$log'];
function MyController($scope, $location, $log) {
}
MyService.$inject = ['$http'];
function MyService($http) {
}
This makes it clear what is getting injected where. And it makes your code much more readable, since you can now write this:
app.module('myModule', ['dep1', 'dep2'])
.controller('MyController', MyController)
.service('MyService', MyService);

Related

Apply jquery after rendering angularJS HTML

i have rendering HTML after AngularJS call
Its controller is
App.controller('controller', ['$scope', '$http', '$sce', '$routeParams', '$location', function ($scope, $http, $sce, $routeParams, $location) {
$http({
//http call
}).then(function (response) {
$scope.requestpurpose = $sce.trustAsHtml(response.data.requestpurpose);
$scope.$watch('requestpurpose', function(newValue, oldValue) {
if(typeof newValue != 'undefined'){
alert(newValue);
showAlreadySelected();
}
});
}]);
and its jquery script is
<script type="text/javascript">
// it will show the div depending on purpose of request
function showAlreadySelected(){
if ($("#1").is(":checked")) {
$("#veterinarian-info").show();
} else {
$("#veterinarian-info").hide();
}
}
</script>
This is my HTML
<div class="row purpose-box" >
<div class="col-sm-12" ng-bind-html="requestpurpose"></div>
</div>
and after ajax call below html is renering in ng-bind-html
<div class="boxes-check">
<div class="box-one">
<input checked="checked" rev="Annual exam" type = "checkbox" name = "request_purpose[]" ng-model=formData.request_purpose[1] onChange="angular.element(this).scope().changePurpose(this)" value = "1" class = "md-check" id = "1" >
</div>
<div class="box-two">
<label title="" for="1">
<span></span>
<span class="check"></span>
<span class="box"></span> Annual exam
</label>
</div>
</div>
<div class="boxes-check">
<div class="box-one">
<input checked="checked" rev="Spay or neuter surgery" type = "checkbox" name = "request_purpose[]" ng-model=formData.request_purpose[2] onChange="angular.element(this).scope().changePurpose(this)" value = "2" class = "md-check" id = "2" >
</div>
<div class="box-two">
<label title="" for="2">
<span></span>
<span class="check"></span>
<span class="box"></span> Spay or neuter surgery
</label>
</div>
</div>
but i am facing problem is after angular load its calling showAlreadySelected function but does not selected "#1" and one thing if any body can help is any Jquery function which will hit whenever input element with id "#1", "#2" render into my ng-bind-html div.
First, I would move the watcher outside the then because you're registering a new watcher everytime you make the ajax call.
I tried, it works to have a number as ID (but not recommended though). We'll need your HTML code as well cause it should work the way you've implemented. Is the #1 node added by the ajax call ( = present in $scope.requestpurpose) or is it always present in the DOM ?
Also, can you add a console.log in the showAlreadySelected function to be sure it's called.
EDIT
App.controller('controller', ['$scope', '$http', '$sce', '$routeParams', '$location', function ($scope, $http, $sce, $routeParams, $location) {
$http({
//http call
}).then(function (response) {
$scope.requestpurpose = $sce.trustAsHtml(response.data.requestpurpose);
showAlreadySelected();
});
}]);
I have bind class with DOMSubtreeModified to detect changes within a div
$('.purpose-box').bind("DOMSubtreeModified",function(){
showAlreadySelected();
});

how to display data in input field using angular js

First off all, I want to show the json data from my codeigniter controller in view page through $http post method.
The problem is that I'm facing some problems, then I can't make it works.
Code:
.state('GetData', {
url: "/getdata",
templateUrl: base_url + "loadl/getdata",
data: {
pageTitle: 'Datapage'
},
controller: "Mycontroller",
resolve: {
deps: ['$ocLazyLoad', function($ocLazyLoad) {
return $ocLazyLoad.load({
name: 'Myapp',
files: [
base_url + 'application/assets/js/controllers/Mycontroller.js'
]
});
}]
}
})
Controller:
angular.module('Myapp')
.controller('Mycontroller', function($rootScope, $scope, $http, $timeout) {
$http.get(base_url + "getData/show").
success(function(response) {
$scope.data1 = response.data;
});
});
CI controller
public function show() {
echo '{"data":[{"sl_num":"1","name":"James","category":"1"}]}';
}
View:
<div class="form-group">
<label class="control-label">Name</label>
<input type="text" placeholder="John" class="form-control" ng-model="data1.name" />
</div>
Upadate with the my answer i will work
angular.module('Myapp')
.controller('Mycontroller', function($rootScope, $scope, $http, $timeout) {
$http.get(base_url + "getData/show").
success(function(response) {
console.log(response);
$scope.data1 = response.data[0].name;
console.log($scope.data1);
});
});
View:
<div class="form-group">
<label class="control-label">Name</label>
<input type="text" placeholder="John" class="form-control" ng-model="data1" />
</div>

Want to send form json data to other server

I have form that outputs data in json using angular there is no database. Now whatever is the output of that form I want to send it to some server Here is the code say I want to send it to server 192.80.36.4 for example. How to do it using post
controller definition code
<body ng-app="submitExample">
<script>
angular.module('submitExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.list = [];
$scope.text = '';
$scope.submit = function() {
if ($scope.text) {
$scope.list.push(this.text);
$scope.text = '';
}
};
}]);
</script>
</script>
<form ng-submit="submit()" ng-controller="ExampleController">
Enter latitude:
<input type="text" ng-model="text" name="text" />
<input type="submit" id="submit" value="Submit" />
<pre>list={{list| json}}</pre>
</form>
You need to use the $http service:
angular.module('submitExample', [])
.controller('ExampleController', ['$scope', '$http', function($scope, $http) {
$scope.list = [];
$scope.text = '';
$scope.submit = function() {
if ($scope.text) {
$scope.list.push(this.text);
$scope.text = '';
$http.post("<your-url>", $scope.list).success(function(data, status) {
console.log(data);
})
}
};
}]);

How to trigger ng-repeat in Angularjs with MVC application..?

i'm creating an application in AngularJS with MVC
i write code in AdminCtrl.js is:
var adminModule = angular.module('angApp', []);
adminModule.controller('AdminCtrl', ['$scope', '$http',
function ($scope, $http) {
//*****get data from Product table
$scope.products = {};
GetAdmin();
function GetAdmin() {
$http({
method: 'GET',
url: '/Admin/GetAdmin',
datatype:'HTML',
}).success(function data() {
$scope.products = data.result;
})
}
}]);
i'm able to get data as collection from back end now using $scope i'm binding it to my view as:
<div id="divTest" ng-controller="AdminCtrl">
<div ng-repeat="item in products">
Prod_ID:{{item.Prod_ID}}
Prod_Name:{{item.Prod_Name}}
Prod_Price:{{item.Prod_Price}}
Prod_Desc:{{item.Prod_Desc}}
</div>
</div>
on the view i'm not able to bind this data using ng-repeat, but this data is visible on console.
please any one help me to figure out the issue what i'm missing.
Thanks in advance.
i did only a little bit mistake, i was binding ng-app to but in the sense it should be bind with now it's working.
my new code like as .....
<body ng-app="angApp">
<script src="Scripts/app/AdminCtrl.js"></script>
<div id="alert" class="alert"></div>
<div ng-controller="AdminCtrl">
<div class="admin-login">
<h2>using angularjs</h2>
<input type="text" id="txtUserAng" placeholder="User Name" ng-model="U_Name" />
<input type="password" id="txtPWDAng" placeholder="Password" ng-model="U_PWD" />
<input type="button" id="login" value="login" ng-click="Login()" />
</div>
</div>
</div>
change
.. }).success(function data() {
$scope.products = data.result;
})..
to
.. }).success(function (data) {
$scope.products = data.result;
})..
ie:
var adminModule = angular.module('angApp', []);
adminModule.controller('AdminCtrl', ['$scope', '$http',
function ($scope, $http) {
//*****get data from Product table
$scope.products = {};
GetAdmin();
function GetAdmin() {
$http({
method: 'GET',
url: '/Admin/GetAdmin',
datatype:'HTML',
//data needs to be inside bracket
}).success(function (data) {
$scope.products = data.result;
})
}
}]);

Angularjs file upload

html
<form method='POST' enctype='multipart/form-data' name="formName">
<div class="row">
<div class="col-md-6">
<input type="file" style="text-align: left" ng-model="value" class="btn"/>
</div>
<div class="col-md-2">
<input type="submit" value="upload" class="btn btn-info" ng-click="submitFile()"/>
</div>
</div>
</form>
AngularJs
$scope.submitFile = function(){
document.formName.action = 'http://xxx.xxx.xxx.xxx:8000/ww/up?s=' + $rootScope.reply.Sid; //$rootScope.reply.Sid is secession id
document.formName.submit();
};
I am trying to do a fileupload with AngularJs. Will this logic work?. My selected path is also coming as given below.
C:\fakepath\license.txt
Is this an error?
Note:
Our UI team was able to the fileupload with the below code. I was trying to attain the same thing in AngularJs
<body>
<form method='POST' enctype='multipart/form-data' action="http://xxx.xxx.xx.xxx:xxxx/yyy/yyyyyyyyy?s=3e3646ea-48cc-4342-a388-e0c0d7bbf4e4"/'>
File to upload: <input type=file id='up_file' name=upfile><br>
</body>
You did it right .. you only have to change few things to make it work
Change
<form method='POST' enctype='multipart/form-data' name="formName">
To
<form action="{{action}}" method='POST' enctype='multipart/form-data' name="formName">
In controller inject $timeout along with $scope
app.controller('Test', function($scope, $rootScope, $timeout){
$scope.submitFile = function(){
$scope.action = 'http://xxx.xxx.xxx.xxx:8000/ww/up?s=' + $rootScope.reply.Sid;
$timeout(function(){
document.formName.submit();
}, 100);
}
});
Action assigning $scope.action with new data .. angularjs needs to update the dom .. that is the reason we are using $timeout and submitting the form
I am providing an example of Upload File. To develop this app, we have used HTML, CSS and AngularJS. Following example shows about how to upload the file using AngularJS.
<html>
<head>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body ng-app = "myApp">
<div ng-controller = "myCtrl">
<input type = "file" file-model = "myFile"/>
<button ng-click = "uploadFile()">upload me</button>
</div>
<script>
var myApp = angular.module('myApp', []);
myApp.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
myApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
}]);
myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){
$scope.uploadFile = function(){
var file = $scope.myFile;
console.log('file is ' );
console.dir(file);
var uploadUrl = "/fileUpload";
fileUpload.uploadFileToUrl(file, uploadUrl);
};
}]);
</script>
</body>
</html>
This is a working example with no other dependencies than AngularJS

Resources