making a url with the $http using routing params error - angularjs

Below is the link of my file. I was unable to generate a url from the existing url generated from $http, by using $parent.$index and $index as ids from routing, please help: Plunker
I have applied the same kind of functionality to another application it worked have a look at this Plunker
Inside the loadSingleMatch() function error in updating the url inside the $http
error image:-
Code
app.controller("selfController", ['$http', '$routeParams',
function($http, $routeParams) {
//create a context
var main = this;
this.parentId = $routeParams.parent;
this.childId = $routeParams.child;
console.log(this.parentId);
console.log(this.childId);
this.urlOne = "https://raw.githubusercontent.com/openfootball/football.json/master/2015-16/en.1.json";
this.urlTwo = "https://raw.githubusercontent.com/openfootball/football.json/master/2016-17/en.1.json";
this.loadSingleMatch = function() {
$http({
method: 'GET',
url: main.urlOne + '/' + main.parentId + '/' + main.childId
}).then(function successCallback(response) {
main.matchData = response.data.rounds[main.parentId].matches[main.childId];
console.log(main.matchData);
}, function errorCallback(response) {
console.log(response);
});
}
}
]);

The a tag should be inside the second ng-repeat:
<div class="w3-row w3-hover-shadow w3-hover-border-black w3-border w3-white w3-padding-16" ng-repeat="x in matchDay.matches">
<a ng-href="#/indiTeam/{{$parent.$index}}/{{$index}}" >
<div class="w3-small">
<div class="w3-col s6 ">
{{x.team1.code}} vs {{x.team2.code}}
</div>
<div class="w3-col s6">
<div class="w3-padding-small">
{{ x.date | date: 'shortDate'}}
({{$parent.$index}} {{$index}})
</div>
</div>
</div>
</div>
</a>
</div>
See modified plunker:
https://plnkr.co/edit/PeqUHIZVC0HsqdjLkdOo?p=preview

Finally found out the answer to my question
the url inside the $http should not be changed only the response inside of it needs to be changed
the url: main.urlOne is the change that bought the output as expected

Related

how to pass parameter from nodejs to angularjs controller?

I have this in nodejs
res.render('pages/dist/reset', {token:req.params.token});
and i can read it in reset.mustache
<body ng-app="eyeApp" ng-controller="ResetController">
<div id="wrapper">
<div id="layout-static">
<div class="static-content-wrapper">
<div class="static-content">
<div id="wrap" ui-view class="mainview-animation animated"></div>
<!--wrap -->
</div>
<footer role="contentinfo" ng-show="!layoutLoading" ng-cloak>
<div class="clearfix">
<button class="pull-right btn btn-default toUp btn-sm hidden-print" back-to-top style="padding: 1px 10px;"><i class="fa fa-angle-up"></i></button>
</div>
</footer>
</div>
</div>
</div>
{{token}}
</body>
Controller from this file is ResetController.
ResetController:
angular
.module('telcoserv.eye.reset', [
'telcoserv.core.services'
])
.controller('ResetController', ['$scope', '$theme','$http','$state','$window','$stateParams', function($scope,$theme,$http,$state,$window,$stateParams) {
'use strict';
$scope.submit = function(){
alert('123');
alert($scope.token);
}
}]);
alert($scope.token) is undefined.
when i say {{token}} in reset.mustache i can read value but $scope.token i can not read in resetController. Why??
$scope.submit = function(){
alert('123');
alert($scope.token);
$http({
method:'',
data: {json : data}
url: ''
}).then(function(response) {
//Success response
}, function(error) {
//Failed response
});
}
use $http to call your api. in method you can put GET, POST, PUT, DELETE, OPTIONS according to your api.
put your URL.
Put your request body in data as JSON only applicable for PUT, POST, DELETE.
If you don't want to initialize some ways to achieve this and get that as parameter
1. Create a constant service for getting token and inject it as a parameter in your controller . you can refer to this article how to create the constant service
https://lostechies.com/gabrielschenker/2014/01/14/angularjspart-9-values-and-constants/
2.On the route definition of the app , make use of the resolve in the route of the page using this controller and use of the same parameter and inject it as a dependency in your controller.

How to dynamically call data from an API when option is selected

Suppose there are two hotels in my options in select tags and I want my h1 to change when I select one of the options. How do I achieve this
I am using POST method to authorize and call data in my reservationCtrl and display the hotel_name in my select tags.
<div class="container">
<div class = "row" ng-controller="reservationCtrl">
<div class="form-group">
<label for="sel1">Select a Hotel:</label>
<select class="form-control" id="sel1">
<option ng-repeat="x in hotels.data">{{x.hotel_name}}</option>
</select>
</div>
</div>
And I am using GET method to call data from another API to display the hotel_name.
<div class="row" ng-controller="showCtrl">
<div class="col-md-4">
<h1 ng-repeat="x in hotel.data">{{x.hotel_name}}</h1>
</div>
</div>
</div>
Here is my showController and I want my hotel id to change like from 72 to 35 when I click one of the options so that it will call data from a different API and display a different name in the headers.
(function(){
angular
.module("reservationModule")
.controller("showCtrl", function($http, $scope, $log){
$http({
method: 'GET',
url: '&hotel_id=72'})
.then(function (response) {
$scope.hotel = response.data;
}, function (reason){
$scope.error = reason.data;
$log.info(reason);
});
});
})();
Here is the reservationController
(function(){
angular
.module("reservationModule")
.controller("reservationCtrl", function($http, $scope, $log){
$http({
url: '',
method: "POST",
data: 'postData',
headers:{ 'Authorization': 'value'}
})
.then(function(response) {
$scope.hotels = response.data;
}
);
});
})();
Yes you can add ng-change and achieve your functionality as below
JS code
var app = angular.module('myApp', []);
app.controller('ctrl1', function($scope) {
$scope.hotels = [{
name: 'Taj',
id: 1
}, {
name: 'Royal',
id: 2
}];
$scope.hotelInfo = {};
$scope.fetchData = function() {
// here call service which will fetch data and assign to hotel data
$scope.hotelInfo = {
address: 'London'
};
}
});
app.controller('ctrl2', function($scope) {
$scope.data = ''
});
HTML code
<div ng-app='myApp'>
<div ng-controller='ctrl1'>
<select ng-options='item as item.name for item in hotels' ng-model='hotel' ng-change='fetchData()'>
</select>
{{hotel}} - {{hotelInfo}}
</div>
</div>
Here is the link Jsfiddle demo
You need to call event on the select box which will call simple function which return the data like following
<select ng-options="size as size.name for size in sizes"
ng-model="item" ng-change="update()"></select>
write javascript code on the update function
Your can use ng-change on select of particular hotel.
In congroller :
$scope.showHotel = function(hotelName){
$scope.selectedHotel = hotelName;
}
<div class="row" ng-controller="showCtrl">
<div class="col-md-4">
<h1 ng-repeat="x in hotel.data" ng-change="showHotel(x.hotel_name)">{{x.hotel_name}}</h1>
</div>
</div>
In view you you can edit like this if you have to display only one hotel name instead of ng-repeat:
<div class="row" ng-controller="showCtrl">
<div class="col-md-4">
<h1>{{selectedHotel}}</h1>
</div>
</div>

iam trying to send data from angular services to nodejs backend Nothing happens

I have enclosed my service function here. Iam trying to send a simple data to node backend but nothing happens. But at this API Endpoint the things works well its saving data in good shape(in postman). Iam sure iam wrong somewhere here in angular No Errors are triggering. No http request is raised.
App.service('UserServices', function($rootScope, $http) {
this.AddToInviteList = function(email, cb) {
var url = $rootScope.api_server_url + "/users/addtoinvitelist";
$http({
method: 'POST',
url: url,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
} // set the headers so angular passing info as form data (not request payload)
}).success(function(data) {
console.log("email is posted sucessfully" + data);
cb(data);
})
}
})
and my controller code is here,
App.controller('InviteController', function($scope, $rootScope, $routeParams, $location, UserServices) {
$scope.AddToInviteList = function(email) {
UserServices.AddToInviteList(email, function(dataresponse) {
console.log(dataresponse);
})
}
});
And my HTML View div is below.
<div class="tab-content">
<!--NEWSLETTER FORM-->
<div class="panel panel-minimalize">
<h2 class="signin-brand animated-hue"> <i class="fa fa-rocket"></i> MEDICOSHERE</h2>
<div class="panel-body bg-inverse ui-corner-all">
<form action="#">
<div class="form-group">
<label for="subcribeNewsletter" class="control-label">INVITE FORM<br> <small>We are happy to invite you to medicoshere, So please enter your email ID in the below form.</small></label>
<div class="input-group input-group-in input-group-sm">
<div class="input-group-addon"><i class="fa fa-envelope text-belpet"></i></div>
<input class="form-control" id="subcribeNewsletter" placeholder="johndoe#mail.com" ng-model="email" required>
<div class="input-group-btn">
<button type="submit" class="btn btn-default text-belpet" ng-click="AddToInviteList(email)"><strong>OK</strong></button>
</div>
</div>
</div><!-- /.form-group -->
</form><!-- /form -->
</div><!-- /.panel-body -->
</div><!-- /.panel -->
<!--/END NEWSLETTER FORM-->
</div><!-- /.cols -->
</main>
Will it would be nice to have a bit more of information regarding your problem but I already see some potential issues.
First of all I hope that App variable (App.service) is an instance of your angular's main module.
Also, I believe you must return the function in an object at the begging or end of your service declaration. That way it'll work as expected when calling it from your controller.
So I believe it should look something like this:
var App = angular.module('myApp');
App.service('UserServices', function($rootScope, $http) {
this.AddToInviteList = function(email, cb) {
var url = $rootScope.api_server_url + "/users/addtoinvitelist";
$http({
method: 'POST',
url: url,
headers: { 'Content-Type': 'application/x-www-form-urlencoded '
}
// set the headers so angular passing info as form data (not request payload) })
.success(function(data) {
console.log("email is posted sucessfully" + data);
cb(data);
})
}
return {
AddToInviteList:AddToInviteList
}
})
Sorry for the bad indentation :) writing from a smartphone.
Hope it helps!
EDIT
Also, are you sure you added the file to your index.html? :D
Another thing to check
You might want to check in your routing is OK. Perhaps you're not associating that view to the right controller. That or not including the service file could be one of the reasons you're not getting any errors.

AngularJS Codeigniter base_url path settings

I am creating a website with Codeigniter 3 and AngularJs. While delevolping i have faced some issues with base url in codeigniter. Im attaching an image file of my directory struture.
In my mainpage(views/home.php) i put a ng-view for loading different pages. Here i am using angularjs ngRoute for routing.
Here is my code.
var myApp = angular.module("myApp",["ui.bootstrap","ui.router","ngRoute"]);
myApp.config(function($routeProvider) {
$routeProvider
.when("/", {
templateUrl : "application/pages/mainpage.php"
})
.when("/about", {
templateUrl : "application/pages/about.html"
})
.when("/services", {
templateUrl : "application/pages/services.html"
})
.otherwise("/",{
templateUrl: "application/pages/mainpage.php"
});
});
Inside that mainpage.php i am listing some profile contents(dummy contents) which is residing inside a json file(datas/data.json). And all the content were listing. And inside this listing i placed a button with ng-click="myName"
Here is the code:
<div class="container" ng-controller="ListController">
<div class="row">
<div class="col-lg-12 text-center">
<h1>Starter Template</h1>
<p class="lead">Complete with pre-defined file paths that you won't have to change</p>
<div class="row">
<div class="col-sm-6 col-md-4 wow zoomIn" data-wow-delay="0.5s" ng-repeat="items in artists">
<div class="thumbnail">
<img ng-src="{{settings.base_url}}/application/assets/images/profile/{{items.shortname}}.jpg" alt="...">
<div class="caption">
<h3>{{items.name}}</h3>
<p>{{items.bio}}</p>
<p>Button Button</p>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- /.row -->
</div>
All my js code were wriiten in app.js(assets/js/app.js) including Angular Js. In this js file i have setup a base_url variable same as in codeigniter config.php file
$config['base_url'] = 'http://localhost/AngularExPack/Angular_Bootstrap_CI_1/';
inside app.js
var base_url= 'http://localhost/AngularExPack/Angular_Bootstrap_CI_1/'
When i click on my button with ng-click="myName" i want to get a controller(Codeigniter controller) and want to execute a function inside that controller. Here iam using auth.php(controllers/auth.php) and function name as functionOne();
public function functionOne()
{
/*$this->load->view('home1');*/
echo "hai";
}
For that iam using $hhtp.post and var base_url for path. But i didnt get that output and it is not passing to that controller.
myApp.controller('ListController', ['$scope', '$http', 'settings', function($scope, $http) {
$http.get('application/datas/data.json').success(function(data) {
$scope.artists = data;
});
$scope.myName = function() {
alert("hai1");
/**/
$http.post(base_url + 'auth/functionOne').success(function(response) {
$scope.data = response
console.log($scope.data);
alert($scope.data);
});
}
}]);
ng-click="myName" function works fine. But it is not passing to the function functionOne inside that controller auth.php. I think the issue is probably with the base_url path. If any one knows this plz help me to solve this issue.
Well, I don't know it this will help you, but this is how I am doing it:
I have this function in a service:
saveFunction: function(obj, user, securityToken){
return $http({
method: 'POST',
url: 'index.php/controller/saveFUnction',
data: $.param({
postID: obj.id ,
csrfTokenName: securityToken,
postName: obj.name,
.....
userID: user.id
}),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
}
if your csrfToken is active in codeigniter config, you need to pass it in your form, as hidden type field. Also, you must set the content type in the headers.

How to "know" the index of ng-repeat in its loop in Angular.JS?

I am new to Angular.JS & are currently working on my first project. I have a page full of entries of the kind
<h1>Title</h1>
<p>Teaser</p>
<p>(a link)</p>
The teaser may include HTML formating or elements like the "&". What I want to do is to "parse" this Teaser so that the formating is "understood" properly by the browser (currently Google Chrome).
The user can click on the link and get to the respective detail page. Here, I already head the same problem, which I could solve by using the ng-bind-html directive as follows:
$scope.shownews = function(id) {
if (typeof id === 'undefined') {
$http({
method: 'GET',
url: 'http://dev.ivm.at/getallnews.php'
}).
success(function(data, status, headers, config) {
$scope.allnews = data;
$scope.myHTML = [];
for (var i = 0; i < $scope.allnews.length; i++) {
$scope.myHTML[i] = $scope.allnews[i].Teaser;
}
});
} else {
$http({
method: 'GET',
url: 'http://dev.ivm.at/getnews.php?ID=' + id
}).
success(function(data, status, headers, config) {
$scope.singlenews = data;
$scope.Newstitel = $scope.singlenews[0].Title
//[...]
$scope.Inhalt = $scope.singlenews[0].Inhalt;
//[...]
$scope.myHTML = "<h1>" + $scope.Newstitel + "</h1><br>" + $scope.Inhalt;
});
}
}
<div data-role="page" id="einenews">
<section class="beitrag" ng-bind-html="myHTML">
<article>
<h1>{{Newstitel}}</h1>
<div class="beitrag-img">
<img src="" + {{Bilderlink}}>
</div>
<p>{{Inhalt}}</p>
</article>
</section>
</div>
For the detail page, an id is passed to the shownews, but the first call is without an id to read all the news from where, the user can reach the detail page by each news link,
I tried to find out how I can use an index in an ng-repeat loop, but couldn't find an answer. Is it possible to find out in HTML how many times the loops executed each time? What I need is something like (in pseudocode):
ng-repeat="news in allnews; count = count + 1;"
or a similar additional tag so that I can use this in a special "myHTMLall".
Thank you for your answer!
EDIT: I modified the code now, but it still does not format the text in the main page with all news:
<div data-role="page" id="allnews">
<div id="sub">
<section class="blog">
<article ng-bind-html="myHTML" ng-repeat="news in allnews">
<h1>{{news.Title}}</h1>
<!-- <p>{{news.Teaser}}</p> -->
<p>{{myHTML[$index]}}</p>
<p class="readmore">
<a href="onenews" ng-click="shownews(news.ID)">
Weiterlesen: {{news.Title}}
</a>
<span class="readmore_icon">
</span>
</p>
</article>
</section>
</div>
</div>
If i'm understanding your question correctly you are looking for AngularJS' built-in $index as described in the documentation for ngRepeat here:
https://docs.angularjs.org/api/ng/directive/ngRepeat

Resources