I'm coding a web app in html, AngularJS and REST (rest modified for my teachers).
My program should load participants in a select in the openning. But show i.e {{participants.name}} and not {{Jhon}}
The problem is at the moment that would load method "search".
Error:
"Error: Birthday.search is not a function
$scope.updateList#localhost:9000/birthday.js:26:1
#localhost:9000/birthday.js:31:5
e#localhost:9000/node_modules/angular/angular.min.js:36:313
Fe/this.$get
HTML:
<!DOCTYPE html>
<html lang="es" data-ng-app="birthdayApp">
<html>
<head>
<meta charset="utf-8">
<script src="node_modules/jquery/dist/jquery.min.js"></script>
<script src="node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="node_modules/angular/angular.min.js"></script>
<link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="css/estilo.css">
<script src="birthday.js"></script>
</head>
[...]
<body>
<div class="container-fluid" data-ng-controller="BirthdayControllers as birthday">
[...]
<select size="2" class="col-lg-12 col-md-12 col-xs-12">
<option data-ng-repeat="participant in participants | filter:filter"> {{participant.name}} </option>
</select>
[...]
The head its ok?
AngularJS
'use strict';
var app = angular.module("birthdayApp", [])
app.factory('Birthday', function($http) {
return function(errorHandler) {
this.search = function(callback, errorHandler) {
$http.get('/participants').success(callback).catch(errorHandler);
}
}
});
/* Controllers */
app.controller("BirthdayControllers", function($scope, Birthday) {
$scope.participants = null;
var errorHandler = function(error) {
$scope.notificarError(error.data);
};
$scope.updateList = function() {
Birthday.search(function(data) { //here stop, here the problem!
$scope.participants = data;
}, errorHandler);
}
$scope.updateList();
[...]
});
My factories look different. Here's how I do mine:
app.factory('Birthday', function ($http) {
return {
search: function() {
return $http.get('/participants');
}
};
});
Controller would look like this:
Birthday.search().success(function(data) {
$scope.participants = data;
}).error(function(data, status, headers, config) {
//handle the error
});
You need to return a factory object from the function not another function.
So modify your code like this:
app.factory('Birthday', function($http) {
return {
search: function() {
return $http.get('/participants');
}
};
});
It's better to handle the callbacks in the controller, so call the factory method like this:
Birthday.search().success(function(data) {
$scope.participants = data;
}).catch(function(error) {
$scope.notificarError(error.data);
});
Related
Angular js filter Working Fine But Throwing Itteration Errors
var app = angular.module('NGapp', []);
app.filter('altDate', altDate);
app.controller('MainCtrl', MainCtrl)
function MainCtrl($scope) {
$scope.data = {
'listProductCost': [{
'data': 1
}, {
'data': 23
}, {
'data': 234
}, ]
}
}
function altDate(_) {
return function(value) {
console.log(value)
if (!value || value.length === 0) {
return [];
} else {
var f = []
angular.forEach(value, function(data) {
f.push(data['data']);
})
var s = []
s.push({
'min': _.min(f),
'max': _.max(f)
})
return s;
}
//return s;
};
}
app.factory('_', LodashFactory);
/** #ngInject */
function LodashFactory($window) {
return $window._;
}
<!DOCTYPE html>
<html ng-app="NGapp">
<head>
<meta charset="utf-8" />
<title>AngularJS </title>
<link rel="stylesheet" href="style.css" />
<script data-require="lodash.js#4.17.4" data-semver="4.17.4" src="https://cdn.jsdelivr.net/npm/lodash#4.17.4/lodash.min.js"></script>
<script data-require="angular.js#1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<md-card-content layout="row" layout-align="none" ng-repeat="datas in data.listProductCost | altDate ">
<div class="dark" flex="30">HO Cost</div>
<div>
<span>{{datas.min}}</span> % to <span>{{datas.max}}</span> %
</div>
</md-card-content>
</body>
</html>
Here is my Working Code With angularjs filter . the filter is working fine but iam getting itteration error in console
the purpose filter is to print only the minimum and maximum value of the discount. can anyone can resolve the issue or give me a idea to resolve this thanks in advance
I see you using lodash. Why not use _.minBy() instead of _.min() ?
That way you can reduce your altDate function to
altDate(_){
return function(value) {
return {
min: _.minBy(value, function(i) { return i.data }),
max: _.maxBy(value, function(i) { return i.data})
}
}
}
The ngTable document does not provide complete information and sample codes and hard to follow. I managed to make bellow code to fetch and display a table from server dynamically. But when I click the table header to sort, the getData (and so the $http) is triggered again, and the result is that after click, the column is not sorted, but the displayed data doubled itself horizontally (say, when open the page, the displayed columns are [id, name], after the click on a column of the table header, it becomes [id, name, id, name]).
<!DOCTYPE html>
<html>
<head lang="en">
<title><%= title %></title>
<meta charset="utf-8">
<script type="text/javascript" src="bower_components/angular/angular.min.js"></script>
<script type="text/javascript" src="bower_components/ng-table/ng-table.min.js"></script>
<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="bower_components/ng-table/ng-table.min.css" />
<script>
(function () {
'use strict';
let app = angular.module('myApp', ['ngTable']);
app.controller('demoCtrl', ['$http', 'NgTableParams', function ($http, NgTableParams) {
let ctrl = this;
ctrl.cols = [];
ctrl.rows = [];
ctrl.tableParams = new NgTableParams({}, {
getData: function (params) {
ctrl.xhr = $http({
method: 'GET',
url: '/ng-table-demo/test_data',
}).then(function (rsp) {
let cols = Object.keys(rsp.data[0]);
for(let i = 0; i < cols.length; i++) {
ctrl.cols.push({field: cols[i], title: cols[i], sortable: cols[i], show: true});
}
ctrl.rows = rsp.data;
return ctrl.rows;
}, function (rsp) {
console.log('http failed.');
});
return ctrl.xhr;
}});
}]);
})();
(function () {
"use strict";
angular.module("myApp").run(configureDefaults);
configureDefaults.$inject = ["ngTableDefaults"];
function configureDefaults(ngTableDefaults) {
ngTableDefaults.params.count = 5;
ngTableDefaults.settings.counts = [];
}})();
</script>
</head>
<body>
<div ng-app="myApp" ng-controller="demoCtrl as ctrl" class="container-fluid">
<h2>ng-table-demo</h2>
<table ng-table-dynamic="ctrl.tableParams with ctrl.cols" class="table table-condensed table-bordered table-striped">
<tr ng-repeat="row in $data">
<td ng-repeat="col in $columns">{{row[col.field]}}</td>
</tr>
</table>
</div>
</body>
</html>
I tried to surround the ctrl.xhr block with bellow, then it stops to duplicate but the sort does not happen anyway.
if(ctrl.xhr === undefined) {
ctrl.xhr = $http...;
}
return ctrl.xhr;
What mistake(s) I made?
The workaround is abandon of getData and set the dataset on xhr succeeded. bellow code worked.
(function () {
'use strict';
let app = angular.module('myApp', ['ngTable']);
app.controller('demoCtrl', ['$http', 'NgTableParams', function ($http, NgTableParams) {
let ctrl = this;
ctrl.cols = [];
$http({
method: 'GET',
url: '/ng-table-demo/test_data',
}).then(function (rsp) {
let cols = Object.keys(rsp.data[0]);
for (let i = 0; i < cols.length; i++) {
ctrl.cols.push({
field: cols[i],
title: cols[i],
sortable: cols[i],
show: true
});
}
ctrl.tableParams = new NgTableParams({}, {
dataset: rsp.data
});
}, function (rsp) {
console.log('http failed.');
});
}]);
})();
Still, I don't know how getData works.
I want show elastic search data on web page that using angular js.
however, not bring data from elasticsearch with that message
Is there anything I need to add or fix in my code?
if anyone answers to me I really appreciate
I have attached an execution screen.
thank you.
Execution screen:
enter image description here
<!doctype html>
<html ng-app="myApp">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<div ng-controller="QueryController"></div>
<script src="node_modules/angular/angular.js"></script>
<script src="node_modules/elasticsearch-browser/elasticsearch.angular.js"></script>
<script>
var myApp = angular.module('myApp', ['elasticsearch']);
// Create the es service from the esFactory
myApp.service('es', function (esFactory) {
return esFactory({ host: 'http://localhost:9200'});
});
myApp.controller('ServerHealthController', function($scope, es, esFactory) {
es.cluster.health(function (err, resp) {
if (err) {
$scope.data = err.message;
} else {
$scope.data = resp;
}
});
});
// We define an Angular controller that returns query results,
// Inputs: $scope and the 'es' service
myApp.controller('QueryController', function($scope, es, esFactory) {
// search for documents
es.search({
index: 'epowersyst',
type: 'logs',
body: {
query:
{
"match_all" : {} }
}
}).then(function (response) {
$scope.hits = response;
console.log($scope.hits)
}).catch(function (err) {
if (err.status === 404) {
alert("error 404" );
} else {
alert("error : " + err );
}
});
});
</script>
</body>
</html>
Okay I'm going to keep this as short as possible.
I've been studying Angular for a bit now and there's still a lot I need to learn, right now I'm trying to figure out how to connect end to end with headers in a service which is completely new to me as I've never done end to end integration.
The code below is provided from another stack overflow answer and what I want to know is how do I connect what they have with say dataService.js. This is all new to me so I'm trying to ask this the best way possible.
<!DOCTYPE html>
<html >
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
</head>
<body ng-app="app">
<div ng-controller="gridController">
<!-- Initialise the grid with ng-init call -->
<div ui-grid="gridOptions" ng-init="GetGridData(urlList)">
</div>
</div>
<script src="Scripts/ng/angular.min.js"></script>
<script src="Scripts/ng-grid/ui-grid.min.js"></script>
<link rel="Stylesheet" type="text/css" href="Scripts/ng-grid/ui-rid.min.css" />
<script type="text/javascript">
var app = angular.module('app', ['ui.grid']);
app.controller("gridController",
["$scope", "$attrs", "$element", "$compile", "$http", "$q",
function ($scope, $attrs, $element, $compile, $http, $q)
{
$scope.urlList = "YourSourceUrl";
function fnGetList(url)
{
var deferred = $q.defer();
$http.get(url)
.success(function (data)
{
deferred.resolve(data);
})
.error(function (errorMessage)
{
alert(errorMessage);
deferred.reject;
});
return deferred.promise;
};
$scope.GetGridData = function (url)
{
console.log("In GetGridData: " + "Getting the data");
// Test Only - un-comment if you need to test the grid statically.
//$scope.loadData = ([
// {
// "UserName": "Joe.Doe",
// "Email": "Joe.Doe#myWeb.com"
// },
// {
// "UserName": "Jane.Doe",
// "Email": "Jane.Doe#myWeb.com"
// },
//]);
//return;
fnGetList(url).then(function (content)
{
// Assuming your content.data contains a well-formed JSON
if (content.data !== undefined)
{
$scope.loadData = JSON.parse(content.data);
}
});
};
$scope.gridOptions =
{
data: 'loadData',
columnDef:
[
{ field: 'UserName', name: 'User' },
{ field: 'Email', name: 'e-mail' }
]
};
}
]);
</script>
</body>
Provided from: How do I get data to show up in angular ui.grid from an $http request
The method I use is to pass the URL as an AJAX call and then wait for the data to get back after which I connect the JSON data to the ng-grid. Note that there will be a delay in getting the data back from the URL and you will have to have a timer that will keep checking for the data return begin valid.
function setCar(){
$.ajax({
type: "POST",
url: '/Test/ConfigConnect.json?details=&car='+car+'&id=1',
dataType: 'json',
success: function(data){
configData = data;
}
});}
The timer function that is part of the javascirpt is also given below.
var timer = setInterval(function() {
$scope.$apply(updatePage);
}, 500);
var updatePage = function() {
if (typeof configData !== 'undefined')
{
clearInterval(timer);
$scope.loadData = configData;
}
};
I am having issues getting the ng-repeat to walkthrough my JSON response, I am new to AngularJS so I am sure its a newbie mistake :). I am trying to have the ng-repeat go through the ns0:AttributeDetails, ns0:Attributes. Here is the JSON data:
{"ns0:GetAgentProfile.Response": {
"xmlns:ns0": "http://URL",
"ns1:Header": {
"xmlns:ns1": "http://URL",
"xmlns:ns7": "http://URL",
"ns1:Source": null,
"ns1:CreatedDateTime": "2014-03-24T09:34:28.339-05:00",
"ns1:MessageType": "Request",
"ns1:MessageId": null
},
"ns0:ProfileDetails": {
"ns0:UserIdentifier": {
"ns0:UserGUID": "2BCF0074-392F-4653-8733-02063C2DBC5C",
"ns0:UserName": "Username01"
},
"ns0:AttributeDetails": {"ns0:Attribute": [
{
"ns0:Name": "AgentLogin",
"ns0:Value": ["Username01"]
},
{
"ns0:Name": "FullName",
"ns0:Value": ["Name, User"]
},
{
"ns0:Name": "LanguageSpoken",
"ns0:Value": ["English|Chinese"]
},
{"ns0:Name": "Supervisor"},
{
"ns0:Name": "Region",
"ns0:Value": ["Region01"]
},
{
"ns0:Name": "Country",
"ns0:Value": ["CO"]
},
{
"ns0:Name": "ClientAccessGroup",
"ns0:Value": ["CountryMobileCCR"]
},
{"ns0:Name": "Roles"}
]},
Here is the HTML:
<!DOCTYPE html>
<html ng-app="auth" xmlns="http://www.w3.org/1999/html">
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<script src="js/bootstrap.js"></script>
<script src="js/angular.js"></script>
<script src="js/authorization.js"></script>
</head>
<body ng-controller="MainCtrl">
<div>
<div class="container-fluid">
<form class="well">
<label>Username:</label>
<input><br><br>
<button ng-click="getData()" class="btn btn-primary">Submit</button>
<button ng-click="clearData()" class="btn btn-danger">Reset</button>
</form>
</div>
<h1>Response from Service:</h1>
<!-- <pre>{{data | json}}</pre> -->
<pre>
Username: {{data['ns0:GetAgentProfile.Response']['ns0:ProfileDetails'] ['ns0:UserIdentifier']['ns0:UserName']}} <br>
Profile Details</pre>
<div ng-repeat="Attribute in data">{{ data['ns0:GetAgentProfile.Response']['ns0:ProfileDetails']['ns0:AttributeDetails']['ns0:Attribute']['ns0:Name'] }}</div>
</div>
</html>
Here is the JS for the controller fetching the data:
var app = angular.module('auth', []);
app.factory('authService', function($http) {
var promise;
var authService = {
async: function() {
if ( !promise ) {
promise = $http.get('package.json').then(function (response) {
console.log(response);
return response.data;
});
}
return promise;
}
};
return authService;
});
app.controller('MainCtrl', function( authService,$scope) {
$scope.clearData = function() {
$scope.data = {};
};
$scope.getData = function() {
authService.async().then(function(d) {
$scope.data = d;
});
};
});
Again I apologize for the newbie question. Any assistance would be greatly appreciated.
Drill down to your array in the repeat directive:
<div ng-repeat="Attribute in data.ns0:GetAgentProfile.Response.ns0:ProfileDetails.ns0:AttributeDetails.ns0:Attribute">
And now you can do:
{{Attribute.ns0:Name}} and {{Attribute.ns0:Value}}
Not sure if the : will play nicely tho, may have to escape those.