angular js calling ng-init on ng-repeat - javascript

I am calling ng-int() on ng-repeat like this:
<ul class="title_page1" style="margin:0; padding:0;">
<li ng-init='some(val.id);' ng-repeat="(key,val) in menu">{{val.name}}</span><span>{{size}}</span></li>
</ul>
I have three elements in menu, by this ng-init is getting called for each ng-repeat but {{size}} from some(val.id). I am getting same size for all the 3 elements. Please kelp me in sorting out this.
$scope.some={function(id){
return $http({
url : 'url+id',
method : 'GET',
async : false,
}).success(function(data) {
$scope.size = data.length;
});
};
$scope.menu=[{java,php,micro}];
And this the thins I am doing but the size i am getting for all the elements is same.
but i have seen in the google but i did not get any result from google

You are retrieving the data for 3 id's, however your saving them in the scope where your controller resides, which can only have one size variable. What I would do is save the size variable into the val object.
<ul class="title_page1" style="margin:0; padding:0;">
<li ng-init='some(val);' ng-repeat="(key,val) in menu">{{val.name}}</span><span>{{val.size}}</span></li>
</ul>
$scope.some={function(val){
return $http({
url : 'url'+val.id,
method : 'GET',
async : false,
}).success(function(data) {
val.size = data.length;
});
};
$scope.menu=[{java,php,micro}];

Related

Passing data from MVC controller to jsTree through ajax calls.

I have a jsTree with a parent node and 5 children nodes. They function fine. I am trying to implement a dynamic jsTree where with click of a node, an ajax call should pass that node's ID to my java MVC spring-boot controller and a Map with keys as child nodes' IDs and value as names of child nodes.
So far I have managed to get the value of the clicked child node's ID and pass it to my java controller through ajax call. But I'm not able to proceed further as I am not sure how to structure the data that is passed from controller to ajax call which in turn has to implement the jsTree.
Here's the code of my existing jsTree -
<div id="container">
<ul>
<li id = "id1">Root
<ul>
<li id="id 1-1">child 1</li>
<li id="id 1-2">child 2</li>
<li id="id 1-3">child 3</li>
<li id="id 1-4">child 4</li>
<li id="id 1-5">child 5</li>
</ul>
</li>
</ul>
</div>
Here's the code of my ajax -jquery call that passes the nodeID to the controller-
$(function() {
$('#container').on('changed.jstree', function (e, data) {
var i, j, r = [], rid = [];
for(i = 0, j = data.selected.length; i < j; i++) {
r.push(data.instance.get_node(data.selected[i]).text);
rid.push(data.instance.get_node(data.selected[i]).id);
}
console.clear();
console.log('Selected: ' + r.join(', '));
console.log('Selected id: ' + rid.join(', '));
$.ajax({
type: 'GET',
url: "http://localhost:8080/tree/object?nodeID="+rid.join(', '),
contentType: 'text/plain',
crossDomain: false,
async:true,
success:function() {
}
});
})
.jstree();
});
I'm limited by my knowledge of jsTree, ajax and jquery. Any help would be appreciated. I am looking into the documentation of jsTree: filling the tree through ajax calls here.
You don't want to do your own AJAX call - You can set a URL to use as per: https://www.jstree.com/api/#/?f=$.jstree.defaults.core.data and JSTree will perform the Ajax calls for you.
set the url property to your url, and data to a function that returns the node id;
'url' : 'ajax_nodes.html',
'data' : function (node) {
return { 'id' : node.id };
}
If returning the data from an Ajax call - you should probably return it in JSON instead, not in HTML.
So this page is what you should be looking at: https://www.jstree.com/docs/json/
The minimum you need is a JSON object like so;
{
id : "string" // will be autogenerated if omitted
text : "string"
children : false
}
Where Children should be true if that node can expand and trigger another all with itself as the ID passed to get its children and false if it is a leaf node.

angularjs: how to store the function returning value in one variable . based on ng-repeat

hi i am getting the intrestedid from ng-repeat , i want to call another service and store that data in one variable dynamically , because need send seperate api for getting images.
my html is look like this
<div class="" ng-repeat="item in items" >
<div ng-init="MyPic = getMyprofile(item.interestedTo)">
<img src="{{MyPic}}">
</div>
</div>
My controller is look like this.
$scope.getMyprofile = function(IntrstdId){
appServices.profile( IntrstdId, function(response){
$scope.meDetails = response.data;
})
return $scope.meDetails;
}
My services is look like this.
service.profile= function(userId, callback) {
path = serviceUrl + '/profile/'+ userId;
$http({
method: 'GET',
url: path
}).then(function(data) {
callback(data)
}, function(data) {});
}
but its getting undefined , any issues in this code.
I tried to resolve this by creating some abstract stub, that may be helpful to you. Please review and let me know if issue still arise
HTML
<div ng-repeat ="data_ in parentData track by $index">
<ul>
<li ng-repeat="result in data_.data track by $index" ng-init="counter=increaseCounter();">
<div ng-model="counter"></div>
</ul>
</div>
Controller
// It simply store variable value in scope.counter
$scope.counter = 0;
$scope.increaseCounter = function () {
var cnt = $scope.counter++;
return cnt;
};
//Another way is to call service while update variable vaule
$scope.counter = 0;
$scope.increaseCounter = function () {
var cnt = $scope.counter++;
AppService.updateValue(cnt);
return cnt;
};
$scope.getMyprofile = function(IntrstdId){
appServices.profile( IntrstdId, function(response){
$scope.meDetails = response.data;
})
return $scope.meDetails;
}
I think issue is this function. appService.profile is asyncronize method and before complete it function return $scope.meDetails;
my suggestion is to hardcore some value like in below and see the result. if it is working then you have to change the function accordingly.
$scope.meDetails ='some value';
return $scope.meDetails;
There are several best practice issue along with the async problem.
1.Avoid using ng-init unless you want to re-run the function when you reconstruct the element, for instance ng-if. It is more so when you use ng-repeat without track by, any changes in the data source would re-trigger all ng-init in the children.
Solution: Run them when you init the controller, or as soon as $scope.items is filled.
angular.forEach($scope.items, function(item) {
appServices.profile(item).then(function(data){
item.myPic = data;
});
});
<div class="" ng-repeat="item in items" >
<img src="{{item.myPic}}">
</div>
2.The correct way to wrap a function that returns promise (which $http is) is to return the function itself. You can research more on how to pass the resolved/rejected result around.
// not needed anymore, just to showcase
$scope.getMyprofile = function(IntrstdId){
return appServices.profile( IntrstdId );
}
// same goes with the service function
service.profile= function(userId) {
path = serviceUrl + '/profile/'+ userId;
return $http({
method: 'GET',
url: path
}).then(function(response) {
return response.data;
});
}

Angularjs $http get json data, but won't display

I am new to angularjs, and I try to async load data by using angularjs.
Json Sample
[{"id":153,"name":"Computer Parts->Cooling Device->CPU Fan"},{"id":30,"name":"Computer Parts->CPU"}]
HTML Code
var homeApp = angular.module('managementApp',[]);
homeApp.controller('categoryMgmt',function($scope,$http){
$scope.categoryFilter = '';
$scope.categorys = '';
$scope.categoryLoad = function(){
var key = $scope.categoryFilter;
$http({
method : 'get',
url : 'hugo.dev/api/categorys/'+key,
}).then(function mySuccess(response){
$scope.categorys = angular.fromJson(response.data);
console.log($scope.categorys[0].name);
});
};
});
<script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
<div class="panel-body" ng-app="managementApp" ng-controller="categoryMgmt">
<div class="form-group col-md-6">
<label for="category">Category</label>
<input name="categoryName" class="form-control" ng-model="categoryFilter">
<div class="list-group" ng-show="categoryFilter" >
<a ng-repeat="item in categorys" href="#" class="list-group-item">{{ item.name }}</a>
</div>
</div>
<button type="button" ng-click="categoryLoad()">asd</button>
</div>
Console Output
Computer Parts->Cooling Device->CPU Fan
The question is, ng-repeat work fine, there are two tags appead in the list,but {{ item.name }} can not read any data. I don't know why.The result #SnapShot, Please Help!
There isn't anything wrong with the code you posted. As Alexander pointed out, you probably don't need fromJson(), but that shouldn't be a problem either.
Here is a working plunker using your same code: https://plnkr.co/edit/GrYZZLjYc9mwCj7dAs5Z?p=preview
The only thing I changed was to pull the data from file since I don't have your service:
// url : 'hugo.dev/api/categorys/'+key,
url: 'data.json'
I guess this isn't necessarily an answer to your problem, but it proves that the code you posted works... your issue must be elsewhere.
scope.categorys must be initialize to array and remove fromJson
homeApp.controller('categoryMgmt',function($scope,$http){
$scope.categoryFilter = '';
// Default to array
$scope.categorys = [];
$scope.categoryLoad = function(){
var key = $scope.categoryFilter;
$http({
method : 'get',
url : 'hugo.dev/api/categorys/'+key,
}).then(function mySuccess(response){
// remove fromJson
$scope.categorys = response.data;
console.log($scope.categorys[0].name);
});
};
I think you should use $scope.category in the html code instead of {{item.category}}.

reusable templates/markup in angularJs

I am working on a project using angularJS, however I'm a bit unsure of the best way to approach this in the framework.
I have an endpoint that makes a request and searches for some data using some parameters, and upon success, it will loop through the table and return matching items.
For each item I make an HTTP call to get some data and the success response would create the scope that would be used in the markup.
How can I reuse the same HTML in the loop AND set/re-set the scope each time so the markup gets generated for each item...or perhaps theres a better 'angular specific' approach.. Thanks
HTML (this is the markup i would like to reuse)
<div class="carouselWrapperOuter">
<div class="carouselWrapper">
<ul rn-carousel rn-carousel-controls rn-carousel-duration="300" class="image carouselholder">
<li ng-repeat="stuff in homeData" class="square" data-url="{{stuff.id}}" ng-click="trackOpen()">
<div class="squareThumb">
<img ng-src="{{stuff.artwork_url}}">
</div>
<div class="itemTitle">{{stuff.title}}</div>
</li>
</ul>
</div>
</div>
JS
angAppFactory.getUser({
where: {
endpointname: "sourcename",
username: "user123"
}
}).success(function(success) {
console.log(success)
//returns a couple of results which would make the following request AND use the markup/set the scope for each item
for (var i = 0; i < success.results.length; i++) {
var endpointid = success.results[i].sourceid
$http({
method: 'GET',
url: 'http://someurl.com'
}).success(function(data) {
//console.log(data)
//scope being set
$scope.homeData = data;
}).error(function() {
alert("error");
});
}
});

Javascript Assign New Field to object

I have a snippet of code here running in a node application
for( i=0; i < Equipment.length; i += 1 ) {
Equipment[i].NumberForSearch = Equipment[i].ClassPrefix + "-" + Equipment[i].UnitNumber;
console.log(Equipment[i].NumberForSearch);
}
console.log(Equipment[0]);
Equipment is an array of objects and I am trying to add a property to each object in that array called "NumberForSearch".
In my application the way we want to display unit numbers for equipment is "ClasssPrefix"-"UnitNumber". The reason I am wanting to join them here into one variable is that inside my angular application, I want the user to be able to type 12345-12345 inside of a search field which then filters out the Equipment. This doesnt work if I have {{ClassPrefix}}-{{UnitNumber}} for obvious reasons, angular doesnt know that the - even exists.
The problem is that inside my for loop everything is checking out fine. Its logging just as its supposed to, so I figured it worked. When I checked the front end and changed it to display "NumberForSearch", nothing showed up.
I then added the logging statement outside the for loop to check just one of my objects to see if the field even existed and it doesnt. So my question is, why is this snippet not adding the "NumberForSearch" field in my object?
You have to make object with this field before setting to $scope's parameter.
Have a look at init() function.
After adding NumberForSearch field we defined array of objects to parameter in scope.
Of course ng-repeat will loop through it and render elements.
So we will add "| filter:query" to show only needed
<div ng-controller="EquipmentController">
<input type="text" ng-model="query.NumberForSearch" placeholder="search">
<ul>
<li ng-repeat="Item in Equipment | filter:query">{{Item.ClassPrefix}}-{{Item.UnitNumber}}</li>
</ul>
</div>
js part:
var App = angular.module('App', []);
App.controller('EquipmentController', function ($rootScope, $scope, $http, $filter) {
$scope.Equipment = [];
$scope.init = function() {
var request = $http({
method: 'get',
url: '/path/to/equipment/resource'
});
request.success(function (response) {
var Equipment = response.Equipment;
for(var i in Equipment) {
Equipment[i].NumberForSearch = Equipment[i].ClassPrefix + "-" + Equipment[i].UnitNumber;
}
$scope.Equipment = Equipment;
$scope.$apply();
});
}
$scope.init();
});
another way of filtering is to send search field to route, in another word we send query to server and it filters response on serverside.
<div ng-controller="EquipmentController">
<input type="text" ng-model="queryNumber" ng-change="searchByNumber()" placeholder="search">
<ul>
<li ng-repeat="Item in Equipment">{{Item.ClassPrefix}}-{{Item.UnitNumber}}</li>
</ul>
</div>
js part:
var App = angular.module('App', []);
App.controller('EquipmentController', function ($rootScope, $scope, $http, $filter) {
$scope.Equipment = [];
$scope.all = function() {
var request = $http({
method: 'get',
url: '/path/to/equipment/resource'
});
request.success(function (response) {
$scope.Equipment = response.Equipment;
$scope.$apply();
});
}
$scope.all();
$scope.searchByNumber = function() {
var request = $http({
method: 'get',
url: '/path/to/equipment/resource?number='+$scope.queryNumber
});
request.success(function (response) {
$scope.Equipment = response.Equipment;
$scope.$apply();
});
}
});

Categories

Resources