Split in Angular JS - angularjs

Here is my code below:
vm.getid = function(){
$http({
method: 'GET',
url: 'api.json',
})
.then(function successCallback(data) {
$scope.id = data.data;
console.log($scope.id);
$scope.split = $scope.id.split('/');
}, function errorCallback(response) {
console.log(response);
console.log('error');
});
};
And here is my html, but it does not work :
<div ng-repeat="s in split">
{{s}}
</div>
Plunker : http://plnkr.co/edit/g1t4pludTTIAJYKTToCK?p=preview
I want to use ng-repeat $scope.split
Thanks!

$scope.id is a list.
What you want to achieve is to get list of lists
The easy way to render it, to use 2 ng-repeats
What about:
<div ng-repeat="i in id">
<div ng-repeat="s in i.split('/')">
{{s}}
</div>
</div>
Demo 1
Or create split list as:
$scope.split = [];
angular.forEach($scope.id, function (item) {
$scope.split.push(item.split('/'));
});
so HTML will look like:
<div ng-repeat="sp in split">
<div ng-repeat="s in sp">
sub: {{s}}
</div>
</div>
Demo 2

printing out id you can see it is an array, not a string
["/big_big_package","/door/cooler","/door/chair","/door","/lets/go/deeper/than/this","/lets/go/deeper","/low"]
and trying to split it gives the following error in console
$scope.id.split is not a function
you can't split an array, you probably want to split each element in the array

Related

Listing Folders AngularJS

I want to ng-repeat some kind of folders, here is my code : HTML:
<div class="container" ng-controller="miControlador">
<li class="left-menu-list-submenu">
<a class="left-menu-link" href="javascript: void(0);" ng-click="vm.getfolders();">
<i class="left-menu-link-icon fa fa-folder"></i>
Catalogs
</a>
<ul class="left-menu-list list-unstyled" style="margin-left:20px;" ng-repeat="fol in folders">
<li>
<a style="cursor:pointer;" ng-click="vm.more_folders();">{{fol}}</a>
<br />
<a style="cursor:default;color:black;" ng-repeat="more in more_folders">
<ul>
<li>{{more}}</li>
</ul>
</a>
</li>
</ul>
</li>
</div>
Js:
var vm = this;
vm.getfolders = function(){
$http({
method: 'GET' ,
url: 'link_folders.json',
})
.then(function successCallback(data) {
console.log("folders");
$scope.folders = data.data;
}, function errorCallback(response) {
console.log(response);
console.log('error');
});
};
vm.getfolders();
vm.more_folders = function(){
$http({
method: 'GET' ,
url: 'more_folders.json',
})
.then(function successCallback(data) {
console.log("more_folders");
$scope.more_folders = data.data;
}, function errorCallback(response) {
console.log(response);
console.log('error');
});
};
vm.more_folders();
link_folders.json:
[
"/visualizer/360",
"/visualizer/2D"
]
more_folders.json:
[
"/visualizer/360/Eva",
"/visualizer/2D/Ferb",
"/visualizer/360/Andy",
"/visualizer/2D/John"
]
Here is my plunker : https://plnkr.co/edit/SW7fqSajpYtQCJdY6wZb?p=preview
What i want - ng-repeat only this objects, which string is like above catalog, something like that -
/visualizer/2D
/visualizer/2D/Ferb
/visualizer/2D/John
Thanks for answers in advance!
What i want - ng-repeat only this objects, which string is like above
catalog, something like that -
/visualizer/2D
/visualizer/2D/Ferb /visualizer/2D/John
To get data filtered like that, All you need is a filter on your second ng-repeat
ng-repeat="more in more_folders | filter: fol ">
This will filter and then print the result which match your fol data.
To read more about filter, refer to this

making a url with the $http using routing params error

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

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>

ng Repeat on a list populated in a $http post shows empty html

I'm really newbie on angularjs, I'm trying to display a list of products so I call a service with $http and in the success function populate the $scope.
All seems works, the $scope.list contains the products but nothing is displayed
I already had a look at this Angularjs $http.get().then and binding to a list and everything looks the same except the "then" function that in my case should be the success function, I suppose. (because if I add that function I get $http(...).then(...).error is not a function).
<div ng-app="myApp" ng-controller="myCtrl">
<ul class="example-animate-container">
<li class="animate-repeat" ng-repeat="item in $scope.list as results">
item {{$index + 1}}:
{{item.Brand}}
</li>
<li class="animate-repeat" ng-if="results.length == 0">
<strong>No results found...</strong>
</li>
</ul>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
var url = "http://localhost:50083/service.asmx/StylesMock";
$scope.list = new Array();
$http({method: 'POST', url: url, headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }})
.success(function(xmlString){
var parser = new DOMParser();
var xml = parser.parseFromString(xmlString, "text/xml");
jsonData = xmlToJson(xml);
mapToScope($scope, jsonData);
})
.error(function(data, status, headers, config) { alert("error"); });;
function mapToScope($scope, data){
angular.forEach(data.ArrayOfStyleData.StyleData, function(value, key) {
$scope.list.push({
Brand : value.Style.Brand,
Name : value.Style.Name,
Image : value.Style.Image,
Price : value.Style.StylePrice
});
});
}
});
Any idea?
Is there a way to understand where the problem is? the console doesn't display errors
As I answered in my comment:
Replace $scope.list by list. By default, angular will look on the relevant controller $scope itself when referenced in your view.
So by specifying $scope.list in your view angular is looking for $scope.$scope.list in your controller
The problem is with your HTML remove $scope because it is already in a angular directive
ng-repeat=item in list
<div ng-app="myApp" ng-controller="myCtrl">
<ul class="example-animate-container">
<li class="animate-repeat" ng-repeat="item in list as results">
item {{$index + 1}}:
{{item.Brand}}
</li>
<li class="animate-repeat" ng-if="results.length == 0">
<strong>No results found...</strong>
</li>
</ul>

ng-repeat doesn't auto refresh after save

I am trying to post some data via save but cannot see the data in the browser unless i refresh, the todo.id is showing straight away but not the todo.name
<body ng-controller="TodoCtrl">
<div ng-repeat="todo in Todos.record">
<div>{{todo.id}} : {{todo.name }}</div>
</div>
<div>
<input ng-model="todo.name" />
<button ng-click="addItem()">Add Item</button>
</div>
</body>
var app = angular.module("myApp",['ngResource']);
app.factory("Todo",function($resource){
return $resource(
"http://localhost/rest/motors/users?app_name=motors",
{},
{
query: {method: 'GET',isArray: true},
get: {method: 'GET'},
save:{method:'POST'}
}
)
})
app.controller("TodoCtrl", function ($scope, Todo) {
"use strict";
$scope.Todos = Todo.get();
$scope.addItem = function(){
Todo.save($scope.todo, function(data){
$scope.Todos.record.push(data);
$scope.todo={};
});
}
})
If that code sample is representative of your real code, it's likely a problem that the "input" field that references "todo.name" is OUTSIDE of the ng-repeat loop, so that is defining a model property outside of your "Todos.record" list.
adding &fields=* in the api url solved the issue. eg changed
"http://myexample.com/rest/motors/users?app_name=motors"
to
"http://myexample.com/rest/motors/users?app_name=motors&fields=*"
Thanks for help.

Resources