AngularJS displaying data from an array - angularjs

I have a controller that returns an array from my django view, i am trying to display each object in a different line in my html but it just returns json.
my controller.js
mainApp.controller('hsController', function($scope, $http, $compile, $timeout, $location) {
$scope.data = {};
$scope.init = function() {
console.log("angular loaded!")
}
$scope.data.form = {
hs_search: "",
result: {},
};
$scope.data.formStyle = {
hs_search: ""
};
$scope.submitForm = function() {
//console.log($scope.data.form)
var error = 0;
if(!$scope.data.form.hs_search) {
$scope.data.formStyle.hs_search = "is_invalid";
error++;
} else {
$scope.data.formStyle.hs_search = "";
}
if(error==0) {
var jsonCall = $http({
method: 'POST',
url:'/theapp/hs-code-search',
data: $scope.data.form,
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
});
jsonCall.success(function(data, status, headers, config) {
if(data.status==1) {
$scope.data.form.result = data.data
console.log($scope.data.form.result)
}
});
jsonCall.error(function(data, status, headers, config) {
if(data.status==0) {
$.growl.error({ message: data.error});
}
});
console.log($scope.data.form)
} else {
$.growl.error({ message: "Please fill the form correctly!"});
}
}
});
my html
<div class="row">
<div class="col-lg-11 col-md-11 mx-auto">
<h3>Search Result For </h3>
<div ng-repeat="chapter_code in data.form.result">
{[{chapter_code}]}
</div>
<div ng-repeat="chapter_desc in data.form.result">
{[{chapter_desc}]}
</div>
</div>
</div>
Result that am getting
What i wanted instead is just the value of each object shown.

Try to convert the JSON to an Object using JSON.parse() and then you can use ng-repeat
myController.js
if(data.status==1) {
$scope.data.form.result = JSON.parse(data.data);
console.log($scope.data.form.result);
// Console shall return an Object
}
HTML
<div class="row">
<div class="col-lg-11 col-md-11 mx-auto">
<h3>Search Result For </h3>
<div ng-repeat="chapterCode in data.form.result.chapter_code">
{{chapterCode}}
</div>
<div ng-repeat="chapterDesc in data.form.result.chapter_desc">
{{chapterDesc}}
</div>
</div>
</div>

Related

How do I get ng-init to work with mutiple functions in a controller?

My html:
<div ng-app="APSApp" class="container">
<br />
<br />
<input type="text" placeholder="Search Terms" />
<br />
<div ng-controller="APSCtl" >
<table class="table">
<tr ng-repeat="r in searchTerms" ng-init="searchTerms=getSearchTerms()" >
<td>{{r.DisplayText}} <input type="text" ng-model="r.SearchInput"></td>
</tr>
</table>
</div>
</div>
<script type="text/javascript">
const moduleId = '#Dnn.ModuleContext.ModuleId';
const tabId = '#Dnn.ModuleContext.TabId';
</script>
<script src="/DesktopModules/RazorCart/Core/Content/Scripts/angular.min.js"></script>
<script src="/DesktopModules/MVC/AdvancedProductSearchMVC/Scripts/AdvancedProductSearch.js"></script>
My angular setup:
var aps = angular.module("APSApp", []);
aps.config(function($httpProvider) {
$httpProvider.defaults.transformRequest = function(data) {
return data !== undefined ? $.param(data) : null;
};
});
aps.factory('SearchTerms',
function($http) {
return {
getSearchTerms: function(onSuccess, onFailure) {
const rvtoken = $("input[name='__RequestVerificationToken']").val();
$http({
method: "post",
url: "/DesktopModules/MVC/AdvancedProductSearchMVC/AdvancedProductSearch/GetAPS",
headers: {
"ModuleId": moduleId,
"TabId": tabId,
"RequestVerificationToken": rvtoken
}
}).success(onSuccess).error(onFailure);
}
};
});
aps.controller('APSCtl',
function(SearchTerms, $scope) {
function getSearchTerms() {
$scope.searchTerms = [];
successFunction = function(data) {
$scope.searchTerms = data;
console.log($scope.searchTerms);
};
failureFunction = function(data) {
console.log('Error' + data);
};
SearchTerms.getSearchTerms(successFunction, failureFunction);
}
function doSomethingElse($scope) {}
});
I'm trying to create a single controller with multiple functions. This works if my angular controller looks like this (and I don't use ng-init):
aps.controller('APSCtl',
function(SearchTerms, $scope) {
$scope.searchTerms = [];
successFunction = function(data) {
$scope.searchTerms = data;
console.log($scope.searchTerms);
};
failureFunction = function(data) {
console.log('Error' + data);
};
SearchTerms.getSearchTerms(successFunction, failureFunction);
});
I was just trying to keep related functions in a single controller. What am I doing wrong? Do I actually have to set up a different controller for each function?
You do not have to assign the value in the template, you can just call the function,
<table class="table" ng-init="getSearchTerms()>
<tr ng-repeat="r in searchTerms" >
<td>{{r.DisplayText}} <input type="text" ng-model="r.SearchInput"></td>
</tr>
</table>
you should have a function named getSearchTerms() in your controller to get it called,
aps.controller('APSCtl',
function(SearchTerms, $scope) {
$scope.getSearchTerms() {
$scope.searchTerms = [];
successFunction = function(data) {
$scope.searchTerms = data;
console.log($scope.searchTerms);
};
failureFunction = function(data) {
console.log('Error' + data);
};
SearchTerms.getSearchTerms(successFunction, failureFunction);
}
function doSomethingElse($scope) {}
});

pushing new elements in angular object

Hy, so I have this code :
angular.forEach(parentsId, function(parentId, key) {
$scope.getContentByParent("Courses",parentId,function(data){
$scope.Courses.push(data);
});
});
$scope.getContentByParent = function(table,parentId,callback) {
var data = new FormData();
data.append('table', table);
data.append('parentId', parentId);
$http.post('../server/Model/content/get_content_by_parent.php', data, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.then(function (data) {
data = data.data;
callback(data);
});
};
and in html
<div class="col-xs-12 col-sm-12" ng-repeat="Course in Courses">
<div class="ribbon ribbon_primary">
<div class="ribbon__title">
{{Course.Name}}
</div>
<div class="ribbon__content" ng-bind-html="Course.Description">
</div>
</div>
</div>
So the problem is that when I push a new element in my object, it pushes it as an array, like this :
[Log] Array (2) (home-controller.js, line 23)
0 [Object] (1)
1 [Object] (1)
Array Prototype
How can I push it as a new object element?
I think I got it :
$scope.getCoursesContent = function(parentsId){
angular.forEach(parentsId, function(parentId, key) {
$scope.getContentByParent("Courses",parentId,function(data){
angular.forEach(data,function(Course, key){
$scope.Courses.push(Course);
});
});
});
};

Data is stuck in $http .then method

Hi I am trying to display my data but when i tried to display it on my html using angular data wont pass through. checked the console and data was there. here is my html.
<ion-view view-title="">
<ion-content>
<!-- <div class="cards">
<div class="item item-image">
<img src="img/banner-children.jpg"></img>
</div>
</div> -->
<div class="list card padding" ng-repeat="charity in charityList">
<a href="#/app/charitypage/{{charity.charity_id}}" class="positive ">
<img class="char-logo img-thumb" ng-src="{{charity.logo}}">
<div class="char-info">
<h3 class="char-name text-pink">
<i class="ion-chevron-right text-pink btn-category"></i>
{{charity.charity_name}}</h3>
<p class="dark">{{charity.description}}</p>
</div>
</a>
</div>
</ion-content>
and here is my controller
angular.module('subCategory.controllers', [])
.controller('subCatCtrl', function($scope, $state, $http) {
$scope.getCategoryList = function(category){
$scope.charityList = {};
var categoryListData = {
charityCategory : category
}
$http({
method: 'POST',
header: {'Content-Type' : 'application/x-www-form-urlencoded'},
url: 'http://localhost/filantrome/Main/getCategoryList',
data: categoryListData
}).then(
function success( response ) {
$scope.charityList= response.data;
console.log($scope.charityList);
$state.go('app.subcat');
},
function error( response ) {
$scope.charityList = response.data;
console.log($scope.charityList);
// handle error
}
);
console.log($scope.charityList);
};
});
i can see the data that i was requesting on the console.log() inside the success function. but when i get out of the .then(); function $scope.charityList is empty.
what am i missing here? thanks!
Seems problem is in state change. To fix this you can use service to store received JSON
angular.module('subCategory.controllers', []).service(charityService, charityService);
/* #ngInject */
function charityService($http) {
var charityList = [];
var service = {
getData: getData,
getCharityList: getCharityList
};
return service;
function getCharityList() {
return charityList ;
}
function getData(categoryListData) {
$http({
method: 'POST',
header: {'Content-Type' : 'application/x-www-form-urlencoded'},
url: 'http://localhost/filantrome/Main/getCategoryList',
data: categoryListData
}).then(
function success( response ) {
charityList = response.data;
console.log(charityList );
$state.go('app.subcat'); // you can also change state here
},
function error( response ) {
$scope.charityList = response.data;
console.log($scope.charityList);
// handle error
}
);
}
}
then post data with controller function
$scope.getCategoryList = function(category){
var categoryListData = {
charityCategory : category
}
charityService.getData(categoryListData);
}
after state changes controller will get charityList from service
angular.module('subCategory.controllers', []) .controller('subCatCtrl',
function($scope, $state, $http, charityService) {
$scope.charityList = charityService.getCharityList();
// ...
As you have posted your console.log output, I can see that you have a single object receiving and assigning to charityList but you have an ng-repeat on the element. So, I think you should change $scope.charityList = {}; to $scope.charityList = []; or you can output this variable in the html to see whats going on like {{charityList}}.

AngularJS calling a rest service with parameter raises syntax error

I have a .net web service containg two methods getUserTasks & getAllTasks(noOfDays) both return valid Json Data. Have verified it with JSONLINT.
var app = angular.module('tasksApp', []);
app.controller('taskController', function($scope, $http, taskGroupFactory) {
$scope.LoadTasks = function(taskFilter, dateFilter) {
console.log(taskFilter + '-' + dateFilter);
if (taskFilter == 'Self') {
$scope.enableFilters = true;
//$scope.taskGroups = taskGroupFactory.getUserTasks();
var getUTasks = taskGroupFactory.getUserTasks();
getUTasks.then(
function(tasks) {
console.log("success");
$scope.taskGroups = tasks.data;
}, function(errorData) {
console.log("Error: " + errorData);
});
};
if (taskFilter == 'All') {
$scope.enableFilters = false;
var getAllTasks = taskGroupFactory.getAllUserTasks(dateFilter);
getAllTasks.then(
function(tasks) {
console.log("success");
$scope.taskGroups = tasks.data;
}, function(errorData) {
console.log("Error: " + errorData);
});
//$scope.taskGroups = taskGroupFactory.getAllUserTasks(dateFilter);
// $scope.taskGroups = taskGroupFactory.getAllUserTasks(dateFilter)
// .success(function (tasks) {
// console.log('success');
// $scope.taskGroups = tasks.data;
// })
// .error(function (error) {
// console.log(error);
// });
};
};
});
app.factory('taskGroupFactory', function($http) {
var factory = {};
var serviceUrl = '/_layouts/SP.TaskDashboard/WebService/TaskService.asmx';
factory.getUserTasks = function() {
//return $http.post(serviceUrl + '/GetMyTasks');
return $http({
method: 'post',
url: serviceUrl + '/GetMyTasks',
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
}
});
};
factory.getAllUserTasks = function(taskDateFilter) {
//var serviceUrl = '/_layouts/SP.TaskDashboard/WebService/TaskService.asmx';
// return $http.post(serviceUrl + '/GetAllTasks', { dateFilter: taskDateFilter })
// .success(function (tasks) {
// return tasks;
// })
// .error(function(errorData) {
// return errorData;
// });
// return $http({
// method: 'post',
// url: serviceUrl + '/GetAllTasks',
// headers: { "Content-Type": "application/json", "Accept": "application/json" }
// });
return $http.post(serviceUrl + '/GetAllTasks', {
dateFilter: taskDateFilter
});
//[{"WebTitle": "Press Releases","WorkflowName": "","Tasks": [{"ID": 1,"Title": "Test","WebTitle": "Press Releases","Status": "Not Started","EncodedAbsoluteUrl": "http://sukcw-vwi-sps02:2010/","ItemLink": "PressReleases/WorkflowTasks/1_.000","WorkflowLink": "","WorkflowName": "","ListId": "9F8054AD-E8C4-47B7-B9DB-24FA05853F31","DueDate": "/Date(1422316800000)/","Created": "/Date(1421327050000)/","ParentItemTitle": "","Classification": "overdue"},{"ID": 2,"Title": "Another Test","WebTitle": "Press Releases","Status": "Not Started","EncodedAbsoluteUrl": "http://sukcw-vwi-sps02:2010/","ItemLink": "PressReleases/WorkflowTasks/2_.000","WorkflowLink": "","WorkflowName": "","ListId": "9F8054AD-E8C4-47B7-B9DB-24FA05853F31","DueDate": "/Date(1422057600000)/","Created": "/Date(1421746613000)/","ParentItemTitle": "","Classification": "overdue"}]}, {"WebTitle": "Test","WorkflowName": "test apprvl workflow","Tasks": [{"ID": 29,"Title": "Please approve 05live-ego","WebTitle": "Test","Status": "Not Started","EncodedAbsoluteUrl": "http://sukcw-vwi-sps02:2010/","ItemLink": "sites/responsive/test/WorkflowTasks/29_.000","WorkflowLink": "http://sukcw-vwi-sps02:2010/sites/responsive/test/Documents/05live-ego.jpg","WorkflowName": "test apprvl workflow","ListId": "6A288BE5-51DD-43BE-B036-4B4A73BFAA5C","DueDate": null,"Created": "/Date(1426854267000)/","ParentItemTitle": " 05live-ego","Classification": "upcoming"}]}]
};
return factory;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="tasksApp">
<div ng-controller="taskController">
<button type="button" class="btn btn-info" ng-click="toggle()">Show Pending Tasks</button>
<div ng-hide="myVar">
<input type="radio" name="taskType" value="Self" ng-model="taskFilter" ng-change="LoadTasks(taskFilter, null)" />My Tasks
<input type="radio" name="taskType" value="All" ng-model="taskFilter" ng-change="LoadTasks(taskFilter,list_day_option)" />All Tasks
<span ng-hide="enableFilters"> show tasks created in last <select ng-options="o.id as o.name for o in list_day_options.data" ng-model="list_day_option" ng-change="LoadTasks(taskFilter,list_day_option)"></select></span>
<div class="btn-group legendWrapper" ng-init="classificationFilter='duetoday'">
Overdue
Due today
Upcoming
Show all
</div>
<div class="panel-group">
<div ng-repeat="t in taskGroups" ng-click="itemClicked($index)" class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">{{t.WebTitle + '-' + '(' + filtered.length + ')'}}</h4>
</div>
<div ng-class="applyToggleClass($index)">
<div ng-repeat="tsk in t.Tasks | filter:t.Classification=getClassificationFilter() as filtered" ng-class="applyTskClass(tsk)">
<span>{{tsk.Title}} </span><span ng-class="applyStatusStyle(tsk)">{{tsk.Status}}</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
Method call to getUserTasks from factory works fine, where as method call to getAllUserTasks(dateFilter) raises syntax error. No error in fiddler, shows the valid json data!! with status 200 but when I debug the script control goes into error block doesnot reach success block :( I have different ways to invoke the service method with parameter but nothing works. As you can see in the comments, feel it is to do with the way I am calling the webservice or passing the parameter to $http.post, please help.
Thanks

How can I use the exact same array from one service in two controllers?

I have this code:
controller:
function deleteRootCategory(){
$scope.rootCategories[0] = '';
}
function getCategories(){
categoryService.getCategories().then(function(data){
$scope.rootCategories = data[0];
$scope.subCategories = data[1];
$scope.titles = data[2];
});
}
getCategories();
service:
var getCategories = function(){
var deferred = $q.defer();
$http({
method:"GET",
url:"wikiArticles/categories"
}).then(function(result){
deferred.resolve(result);
});
}
return deferred.promise;
}
html:
<div ng-controller="controller">
<div ng-repeat="root in rootCategories"> {{root}} </div>
<div ng-repeat="sub in subCategories"> {{sub}} </div>
<div ng-repeat="title in titles">{{title}}</div>
</div>
html2:
<div ng-controller="controller">
<div ng-include src="html"></div>
<button ng-click="deleteRootCategory()">Del</button>
</div>
When I click the deleteRootCategory-button the array $scope.rootCategories is updated, but the view won't ever change.
What am I missing?
Thanks
You will probably want to have a broadcast event set up when the value is changed in the service. Something like this.
.service("Data", function($http, $rootScope) {
var this_ = this,
data;
$http.get('wikiArticles/categories', function(response) {
this_.set(response.data);
}
this.get = function() {
return data;
}
this.set = function(data_) {
data = data_;
$rootScope.$broadcast('event:data-change');
}
});
Have both controllers waiting for the event, and using the set to make any changes to the array.
$rootScope.$on('event:data-change', function() {
$scope.data = Data.get();
}
$scope.update = function(d) {
Data.set(d);
}

Resources