AngularJS : having multiple functions in a controller - javascript

I have a simple controller in AngularJS, and i would like it to have 2 different functions :
var app = angular.module('searchApp', []);
app.controller('searchCtrl', function($scope, $http, $log) {
//1st function
$scope.search = function() {
$http.post('server.php', { "data" : $scope.keywords})
.success(function(data, status) {
$scope.result = data;
})
};
//2nd function
$scope.tableClick = function() {
$log.log('Hello World!');
};
})
I think there's an issue somewhere in the syntax because this script works only when i remove the 2nd function.
When i use the script with the 2 functions (so, what i posted), i get {{ x }} for the following html elements :
<tr ng-repeat="x in result">
<td><a href="wwww.test.com" >{{ x }}</a></td>
Any clues ?

As I said in the comments, there's no echo 'Hello World!' in javascript. If you want to write that phrase on the DOM, then you have to use it as a simple expression. Just like:
$scope.helloWorld = 'Hello World!';
and then in the HTML you simply call it like {{helloWorld}}.
I'm seeing you're testing it with a function. In this case you should return the string 'Hello World!' like
$scope.helloWorld = function () {
return 'Hello World';
};
In the HTML:
{{ helloWorld() }}
In the case you want to simply "log" the Hello World! to the browser's console (which I doubt because you're not paying attention to JS errors): DO NOT USE console.log();. Use AngularJS' built-in service $log instead
A better code
Anyway, if I were you, I'd write that code differently. See
var app = angular.module('searchApp', []);
app.controller('searchCtrl', function ($scope, $http, $log) {
//1st function
$scope.search = function () {
$http.post('server.php', { "data" : $scope.keywords })
.then(function (resp) { //use then instead of success/error
return resp.data;
}, function inCaseOfErrors (err) { //named just for teaching purposes
$log.log(err);
});
};
//2nd function
$scope.tableClick = function () {
$log.log('Hello World!');
};
})

Please make sure that your $scope.result has the right values. Also note that echo doesn't exist in javascript.
In the code below, I took away the server-call and used hard-coded data, just to test:
var app = angular.module('searchApp', []);
app.controller('searchCtrl', function($scope, $http) {
$scope.result = ["apple", "orange", "raisin", "banana"];
//1st function
$scope.search = function() {
//$http.post('server.php', { "data" : $scope.keywords})
//.success(function(data, status) {
//$scope.result = data;
//})
};
//2nd function
$scope.tableClick = function(item) {
console.log("someone clicked the table! Row: " + item);
};
})
Html:
<table>
<tr ng-repeat="item in result">
<td data-ng-click="tableClick(item)">{{ item }}</td>
</tr>
</table>

Related

API, angularJS, to get datas

I never done angularJS from all my life and i am lost.
So i have done this file, to obtain datas from an api with a filter of time.
forecast.js
(function() {
angular.module('application').factory('Forecast', ['$http', '$q', function($http, $q){
var ApiAddr = "api.com/";
forecast.getResults = function(timeStart, timeEnd){
// We map application varaible names with API param names
var httpParams = {
type: "global",
time: "minute",
tsmin: timeStart,
tsmax: timeEnd
};
return $http.get(apiAddr, {
params: httpParams,
cache: true
}).then(function(data){
return data;
},
function(response){
console.log(
"HTTP request "+ApiAddr+
" (with parameters tsmin="+httpParams.tsmin+", tsmax="+httpParams.tsmax+
", type="+httpParams.type+", time="+httpParams.time+
(httpParams.motive ? ", motive="+httpParams.motive : "")+
(httpParams.vector ? ", vector="+httpParams.vector : "")+
(httpParams.media ? ", media="+httpParams.media : "")+
") failed with "+response.status
);
return $q.reject(response);
}
);
}];
But i have no idea to make a controller adapter to this. What type of controller i can do ?
Every exemple are based on a fixed json file, with no parameters.
Moreover, i want, in HTML to imput the time filter, but i have totaly no idea of what to do for this. The example i have seen were to get datas, no to send.
Ps : I have made 2 days of research about this, i have never done front end programming in my life.
(function() {
angular.module('application', [])
.factory('Forecast', ['$http', '$q', function($http, $q) {
var apiaddress = 'api.com';
var forecast = {};
forecast.getResults = function(timeStart, timeEnd) {
// We map application varaible names with API param names
var httpParams = {
type: "global",
time: "minute",
tsmin: timeStart,
tsmax: timeEnd
};
return $http.get(apiaddress, {
params: httpParams,
cache: true
}).then(function(result) {
return result.data;
});
};
return forecast;
}])
.controller('SampleCtrl', ['$scope', 'Forecast', function($scope, Forecast) {
$scope.forecastReport = '';
$scope.getForecast = function() {
Forecast.getResults($scope.timeStart, $scope.timeEnd)
.then(function(report) {
$scope.result = report;
}).catch(function(err) {
$scope.result = '';
console.error('Unable to fetch forecast report: ' + err);
});
};
}]);
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="application" ng-controller="SampleCtrl">
<label>Time Start:
<input type="text" ng-model="timeStart"/></label>
<label>Time End:
<input type="text" ng-model="timeEnd"/></label>
<button ng-click="getForecast()">Get Forecast</button>
<hr/>
<div>
<b>Forecast Result:</b>
</div>
<pre>{{forecastReport | json}}</pre>
</div>
Just inject the factory into your controller like this:
var app = angular.module('application');
app.controller('myController',
['$scope', 'Forecast', function($scope, Forecast) { /* access to Forecast*/}]);
Or with a component (cleaner):
app.component('myComponentCtrl', {
templateUrl: 'template.html'
controller: myComponentCtrl
})
myComponentCtrl.$inject = ['$scope', 'Forecast'];
function myComponentCtrl($scope, Forecast) {/* ... */ }

Retrieving JSON data from API using AngularJS

I'm trying to get data from a Web API and display it in a table, but it doesn't work.
I am new to angularjs and i code simple program to get data from the Web API and display in table.but i am not able to get data.
Module
var app = angular.module("myApp", []);
Service
app.service("myService", function ($http) {
//get All Eployee
this.getEmployees = function () {
return $http.get('http://apidemo.gouptechnologies.com/api/admin');
};
})
Controller
app.controller("myCntrl", function ($scope, myService) {
$scope.divEmployee = false;
GetAllEmployee();
function GetAllEmployee() {
alert('home');
var getData = myService.getEmployees();
getData.then(function (emp) {
$scope.employees = emp.data;
}, function () {
alert('Error in getting records');
});
}
});
The JS code is included in the head tag of the HTML file.
HTML body
<body>
<div ng-app="myApp" ng-controller="myCntrl">
<ul>
<li ng-repeat="x in employees">
{{ x.username + ', ' + x.password }}
</li>
</ul>
</div>
</body>
The API URL is legitimate.
Thanks.
Let example a json file in "data/branchList.json" directory, And i am trying to access all data from json file using $http.
It may help you to call a rest service aslo. check this example
data/branchList.json
[
{
"branch_id": 1,
"branch_name": "Mummbai",
"branch_address": "India"
},
{
"branch_id": 2,
"branch_name": "New York",
"branch_address": "US"
}
]
Controller
angular.module('myApp')
.controller('myCntrl', ['$http', '$state', function ($http, $state) {
'use strict';
var vm = this;
function init(){
vm.branchs = '';
loadBranch();
}
init();
function loadBranch(){
$http.get('data/branchList.json').success(function(response){
vm.branchs = response;
})
}
}]);
In this example i am storing all the data in vm.branches variable, you can use this variable in html page
HTML
<li class="col-sm-6" ng-repeat = "branch in vm.branchs">
<strong>{{branch.branch_name}}</strong>
<span>{{branch.branch_address}}</span>
</li>

Problems with ng-repeat, $scope, $http

im working with AnuglarJS 1.4.8. I want give out the data with ng-repeat.
I have the following problem and i have no more ideas to solve it. I tried the solutions from AnuglarJS but i doesnt work.
Could someone help me please.
Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: []
http://errors.angularjs.org/1.4.8/$rootScope/infdig?p0=10&p1=%5B%5D
Service:
.service('database', function ($http) {
self = this;
this.url = 'http://localhost:3001';
this.getPersons = function(cb){
return $http({
method: 'GET',
url: self.url + '/loadperson'
}).success(function (data) {
cb(data);
});
};
});
Controller:
angular.module('myApp')
.controller('personCtrl', function ($scope, database) {
$scope.people = function(){
return{
getAll: function () {
database.getPersons(function (data) {
return data;
// should return a Object(id, name)
});
}
}
};
HTML:
<div ng-repeat="people in people().getAll()">
<p>{{people.name}}</p>
</div>
You are missing the non-blocking way of javascript. Try following, it should work
Controller:
angular.module('myApp')
.controller('personCtrl', function ($scope, database) {
$scope.loadPeoples = function(){
return{
getAll: function () {
database.getPersons(function (data) {
$scope.peoples = data;
// should return a Object(id, name)
});
}
}
};
$scope.loadPeoples();
})
HTML:
<div ng-repeat="people in peoples">
<p>{{people.name}}</p>
</div>
Try that.
Service:
.service('database', function ($http) {
self = this;
this.url = 'http://localhost:3001';
this.getPersons = function(){
return $http({
method: 'GET',
url: self.url + '/loadperson'
});
};
});
Controller:
angular.module('myApp')
.controller('personCtrl', function ($scope, database) {
database.getPerson().success(function(data) {
$scope.people = data;
});
});
HTML:
<div ng-repeat="person in people">
<p>{{person.name}}</p>
</div>
You should also be aware that you shouldn't return each time a NEW array for iterating. Otherwise angular will keep calling that function for retrieving a "stable" value for the array.
You've made a common error in javascript when running asynchronous queries. The pattern goes:
function outerFunction() {
invokeInnerFunction(function() {
return 3;
}
}
What does outerFunction() return? An error is to think it returns 3, but the answer is actually that outerFunction doesn't return anything.
Likewise, in your example getAll isn't actually returning anything; it's just calling an asynchronous method. This asynchronous method invoked $http, which triggers a digest loop which will result in getAll being called again, and so on for ever. Be thankful that angular can detect this problem.
You only want to call the database query once on startup, and initialize the list of people. Simply store this list in a variable so it won't query the database again on the next digest loop.
angular.module('myApp')
.controller('personCtrl', function ($scope, database) {
$scope.allPeople = [];
database.getPersons(function(data) {
$scope.allPeople = data;
});
};
An then for your HTML
<div ng-repeat="people in allPeople">
<p>{{people.name}}</p>
</div>
Much simpler.
Have you tried making a separate function to fetch the entities from the data base, then put this data in a variable, that you then will pass to the ngRepeat ?
your controller
angular.module('myApp')
.controller('personCtrl', function ($scope, database) {
$scope.people = [];
$scope.getPeople = function(){
return{
getAll: function () {
database.getPersons(function (data) {
$scope.people = data;
return;
// should return a Object(id, name)
});
}
}
//load the list of people
$scope.getPeople();
};
your view
<div ng-repeat="person in people">
<p>{{person.name}}</p>
</div>

ng-show - using a service as a scope parameter

I'm writing an angular 1.5.0-rc0 application using bootstrap for a nav bar component.
I want to show the user an added items to his navigation bar if his user group id is 1.
first I created a service:
app.factory('UserService', function() {
return {
userGroupId : null
};
});
I created the nav bar as a directive, so i included it in the main html file
<nav-bar></nav-bar>
and the nav-bar directive code:
(function () {
angular.module('myalcoholist').directive('navBar', function () {
return {
restrict: 'E',
templateUrl: 'views/nav.html',
controller: ['$scope','$auth', 'UserService',function ($scope,$auth,UserService) {
$scope.user=UserService;
$scope.isAuthenticated = function()
{
return $auth.isAuthenticated();
};
}]
}
});
})();
as you can see I set $scope.user as the returned object from UserService.
in my login controller, after a successful login I set the userGroupId.
angular.module('myalcoholist').controller('LoginController',['$scope','$auth','$location', 'toastr','UserService',function ($scope,$auth,$location,toastr,UserService) {
$scope.authenticate = function (provider) {
$auth.authenticate(provider).then(function (data) {
var accessToken = data.data.token;
apiKey=accessToken;
UserService.userGroupId=data.data.user_group_id;
...
now.. my nav-bar template file is as the following code:
<li ng-show="user.userGroupId == 1">
Admin Drinks
</li>
even after the authentication, when I uset userGroupId to 1 the element is still not shown.
any ideas?
update
I debugged and noticed that UserService.userGroupId is still null. so
I changed the UserService to have the following code:
app.factory('UserService', function() {
var user = {userGroupId:null};
return {
setUserGroupId: function (userGroupId) {
user.userGroupId=setUserGroupId;
},
getUserGroupId: function () {
return user.userGroupId;
}
};
});
in my LoginController I now try to execute setUserGroupId:
angular.module('myalcoholist').controller('LoginController',['$scope','$auth','$location', 'toastr','UserService',function ($scope,$auth,$location,toastr,UserService) {
$scope.authenticate = function (provider) {
$auth.authenticate(provider).then(function (data) {
var accessToken = data.data.token;
apiKey=accessToken;
UserService.setUserGroupId(data.data.user_group_id);
...
when I debug i see that userService is an object with two functions as I defined, but when the javascript chrome debugger tries to execute this line:
UserService.setUserGroupId(data.data.user_group_id);
I get the following error:
ReferenceError: setUserGroupId is not defined
at Object.setUserGroupId (app.js:21)
at login-controller.js:12
at angular.js:15287
at m.$eval (angular.js:16554)
at m.$digest (angular.js:16372)
at m.$apply (angular.js:16662)
at g (angular.js:11033)
at t (angular.js:11231)
at XMLHttpRequest.v.onload (angular.js:11172)
I have created a fiddle showcasing your requirement (as close as possible), and it seems to work fine.
http://jsfiddle.net/HB7LU/21493/
My guess is that you aren't actually setting the value when you think you are, and will likely require some debugging. Here is the code for brevity.
HTML
<div ng-controller="MyCtrl">
<div ng-click="clicked()">
Click ME, {{user.value}}!
</div>
<test-dir></test-dir>
</div>
JS
angular.module('myApp',[])
.service('TestService', function(){
return {
value: 2
};
})
.directive('testDir', function(){
return {
restrict: 'E',
template: '<div ng-show="user.value === 1">Here is some text</div><div>Some more always showing</div>',
controller: function ($scope, TestService) {
$scope.user = TestService;
}
};
})
.controller('MyCtrl', function($scope, TestService){
$scope.user = TestService;
$scope.clicked = function(){
TestService.value = 1;
};
});

I am unable to access an asp.net mvc controller to return me a JsonResult using $resource of angular

What am I missing ? I am new to Angularjs. Trying angularjs with asp.net mvc. I am unable to access an asp.net mvc controller to return me a JsonResult using $resource of angular.
However, I get success otherwise using $.getJson of javascript but not using angularjs. What am I missing ? please guide. Thank you for replying any.
Following is my Service
EbsMvcApp.factory('classListService', function ($resource, $q)
{
var resource = $resource
(
'/Home/ClassList'
, {}
//{ method: 'Get', q: '*' }, // Query parameters
, { 'query': { method: 'GET' , isArray:false } }
);
function get($q)
{
console.log('Service: classListServic > Started');
var Defered = $q.defer();
resource.get
(
function (dataCb)
{
console.log('success in http service call');
Defered.resolve(dataCb);
}
, function (dataCb)
{
console.log('error in http service')
Defered.reject(dataCb);
}
);
return Defered.promise; // if missed, would throw an error on func: then.
};
return { get: get };
});
angular Controller:
var EbsMvcApp = angular.module('myApp', ['ngResource']);
//'classListService',
EbsMvcApp.controller
(
'myAppController',
['$scope','classListService','$q' , function ($scope, classListService, $q)
{
console.log('controller myAppController started');
var classList = classListService.get($q);
classList = classList.then(
function ()
{
(
function (response)
{
console.log('class list function response requested');
return response.data;
}
);
}
);
console.log(classList.ClassName);
console.log(classList);
console.log('end part of ctrl');
$scope.classList = classList;
$scope.SelectedClassID = 0;
$scope.message = ' message from Controller ';
}
]
);
Asp.net MVC Controller
namespace EBS_MVC.Controllers
{
public class HomeController : BaseController
{
ApplicationDbContext db = new ApplicationDbContext();
public JsonResult ClassList()
{
var List = new SelectList(db.tblClass, "ID", "ClassName");
return Json(List, JsonRequestBehavior.AllowGet);
}
}
}
Brower's response (F12):
ControllerTry1.js:11 controller myAppController started
serviceGetClassList.js:16 Service: classListServic > Started
ControllerTry1.js:28 undefined
ControllerTry1.js:29 c
ControllerTry1.js:31 end part of ctrl
angular.js:12520 Error: [$resource:badcfg]
[Browers response: screen shot][1]
Oky, finally, I got a solution using the $http service. from here
http://www.infragistics.com/community/blogs/dhananjay_kumar/archive/2015/05/13/how-to-use-angularjs-in-asp-net-mvc-and-entity-framework-4.aspx
in csHtml file, a reference to the service.js and Controler.js is required.
I am not sure if I have added it earlier or later now. but its required.
ng-Controller:
EbsMvcApp.controller('ClassListController', function ($scope, ClassListService2) {
console.log('ClassListController Started');
GetClassList();
function GetClassList()
{
ClassListService2.GetJson()
.success(function (dataCallBack) {
$scope.classList = dataCallBack;
console.log($scope.classList);
})
.error(function (error) {
$scope.status = 'Unable to load data: ' + error.message;
console.log($scope.status);
});
}
});
ng-Service:
EbsMvcApp.factory('ClassListService2', ['$http', function ($http) {
console.log('ClassListService2 Started');
var list = {};
list.GetJson = function () {
return $http.get('/Home/ClassList');
};
return list;
}]);
csHtml View:
<div class="text-info" ng-controller="ClassListController">
<h3> Text from Controller: </h3>
#*table*#
<table class="table table-striped table-bordered">
<thead>
<tr><th>DisplayName</th><th>Value</th>
</thead>
<tbody>
<tr ng-hide="classList.length">
<td colspan="3" class="text-center">No Data</td>
</tr>
<tr ng-repeat="item in classList">
<td>{{item.Text}}</td>
<td>{{item.Value}}</td>
</tr>
</tbody>
</table>
Sorry for the delay, I just wrote up some code to quickly test the ngResource module as I haven't used it yet.
I've got the code working to do what you want using the ngResource module. I think part of the problem was that you was configuring the query method but calling the get method so your configurations was not applied.
Here is the service class that I wrote to test against a controller the same as yours.
(function () {
'use strict';
angular
.module('myApp')
.service('classService', ClassService);
ClassService.$inject = ['$resource', '$q'];
function ClassService($resource, $q) {
var resource = $resource
(
'/Home/ClassList',
{},
{
'get': { method: 'GET', isArray: true },
'query': { method: 'GET', isArray: true }
}
);
var service = {
get: get
};
return service;
////////////
function get() {
var Defered = $q.defer();
resource.get(function (dataCb) {
console.log('success in http service call');
Defered.resolve(dataCb);
}, function (dataCb) {
console.log('error in http service')
Defered.reject(dataCb);
});
return Defered.promise;
};
};
})();
The controller looks like this
(function () {
'use strict';
angular
.module('myApp')
.controller('classController', ClassController);
ClassController.$inject = ['$scope', 'classService'];
function ClassController($scope, classService) {
var vm = this;
vm.data = null;
activate();
/////////////
function activate() {
var classList = classService.get().then(function (response) {
console.log('class list function response requested');
vm.data = response;
console.log(vm.data);
});
console.log('end part of ctrl');
$scope.SelectedClassID = 0;
$scope.message = ' message from Controller ';
};
};
})();
I've included some of your original code just so you can see how it would fit in.
Glad to see you have got it working though!

Categories