I need to use ng-repeat with ng-bind to display data into a table but what I have tried doesn't display any data,where am I going wrong with the code that I tried?
HTML:
<tbody id="ngDowntimeBody">
<tr ng-repeat="previousdowntime in GetPreviousDowntimeEvents.PreviousDowntimeEvents">
<td ng-bind="previousdowntime.CategoryId"></td>
<td ng-bind="previousdowntime.StartTime"></td>
<td ng-bind="previousdowntime.EndTime"></td>
<td ng-bind="previousdowntime.Comment"></td>
</tr>
</tbody>
JS:
function GetPreviousDowntimeEvents($http) {
var self = this;
self.PreviousDowntimeEvents = [];
self.AjaxData = ngHesto.Ajax.Get($http
, {
url: PREVIOUS_DOWNTIME_EVENTS
, success: function (data) {
self.PreviousDowntimeEvents = data.data[0];
console.log(self.PreviousDowntimeEvents);
}
});
}
var ngAppModule = angular.module('myApp', []);
ngAppModule.controller('DowntimeController', ['$scope','$http', function ($scope, $http) {
$scope.GetPreviousDowntimeEvents = new GetPreviousDowntimeEvents($http);
}]);
The Data doesn't get displayed
This is the response I get back:
{EventId: "10", DepartmentId: "7", CategoryId: "10", StartTime: "2014-08-19T10:00:00", EndTime: "2014-08-19T10:10:00",Comment:"Test"}
JS
function GetPreviousDowntimeEvents($http) {
var self = this;
self.PreviousDowntimeEvents = [];
self.AjaxData = ngHesto.Ajax.Get($http
, {
url: PREVIOUS_DOWNTIME_EVENTS
, success: function (data) {
self.PreviousDowntimeEvents = data.data;
console.log(self.PreviousDowntimeEvents);
}
});
}
var ngAppModule = angular.module('myApp', []);
ngAppModule.controller('DowntimeController', ['$scope','$http', function ($scope, $http) {
$scope.GetPreviousDowntimeEvents = new GetPreviousDowntimeEvents($http);
}]);
HTML
<tbody id="ngDowntimeBody">
<tr ng-repeat="previousdowntime in GetPreviousDowntimeEvents.PreviousDowntimeEvents">
<td>{{previousdowntime.CategoryId}}</td>
<td>{{previousdowntime.StartTime}}</td>
<td>{{previousdowntime.EndTime}}</td>
<td>{{previousdowntime.Comment}}</td>
</tr>
</tbody>
</table>
I guess you do not need this new staff there
instead of
ngAppModule.controller('DowntimeController', ['$scope','$http', function ($scope, $http) {
$scope.GetPreviousDowntimeEvents = new GetPreviousDowntimeEvents($http);
}]);
use either
ngAppModule.controller('DowntimeController', ['$scope','$http', GetPreviousDowntimeEvents]);
or return something in your GetPreviousDowntimeEvents function
function GetPreviousDowntimeEvents($http) {
//...
return self;
}
Related
I have looked at a number of other questions related to this such as
AngularJS : ng-repeat list is not updated when a model element is spliced from the model array
ng-repeat not updating on update of array
However I think that the way I built my app is sufficiently different that these aren't helping me.
I think my idea of doing this:
$rootScope.$on('connectionDispositionChanged',function(event, item){
$scope.data.matches[item.index].info.disposition = item.disposition;
});
Isn't really working out the way I had hoped. I can actually see in the console that this updating, but it doesn't update in the table. Adding $scope.$apply() after this causes a digest in-progress error.
show.phtml
<div class="container-fluid" ng-app="analysisApp" ng-controller="analysisController">
<table class="table table-condensed">
<thead>
<tr >
<th ng-repeat="header in baseColumns" class="text-center">{{header.name | tableHeader}}</th>
<th ng-repeat="header in comparisonColumns" class="text-center text-info">{{header.name | tableHeader}}</th>
<th> </th>
</tr>
</thead>
<tbody>
<tr table-row data="data" ng-repeat="item in data.matches | filter:searchMatchText track by $index">
</tbody>
</table>
<row class="col-md-12 text-center"><span class="text-muted">End of Data</span></row>
</div><!-- #matches -->
</div>
tableRowDirective.js
"use strict";
analysisApp.directive("tableRow", function($compile) {
var getTemplate = function(scope, element, attrs){
var base = scope.item.base;
var comp = scope.item.comparison;
var info = scope.item.info;
// other non-relevant code...
returnString += '<td class="text-center"><button class="btn btn-default btn-xs" ng-click="matchesSetDisposition(item, data.settings, $index)" >Set Disposition</button>';
returnString += '</td>';
return returnString;
};
var linker = function(scope, element, attrs){
element.html(getTemplate(scope, element, attrs));
$compile(element.contents())(scope);
};
return {
restrict : "A",
replace : true,
link: linker
};
});
analysisController.js
"use strict";
analysisApp.controller('analysisController', ['$scope','$rootScope','loadData','saveData','$uibModal', function ($scope, $rootScope, loadData, saveData, $uibModal, $log) {
$rootScope.$on('connectionDispositionChanged',function(event, item){
// $scope.data.matches[item.index].info.disposition = item.disposition;
});
$scope.matchesSetDisposition = function(item, scope, index){
var modalInstance = $uibModal.open({
animation: $scope.animationsEnabled,
templateUrl: '/angular/analysis/templates/matches-modal.html',
controller: 'matchesModalController',
size: 'lg',
resolve: {
itemData: function () {
return {
dispositionLabels: $scope.dispositionLabels,
disposition: item.info.disposition,
connectionID: item.info.id,
comparisonID: comparisonID,
baseItemID: item.base.id,
baseTitle: itemTitle(item.base),
comparisonItemID: item.comparison.id,
comparisonTitle: itemTitle(item.comparison),
index: index
}
}
}
});
modalInstance.result.then(function (item) {
$scope.data.matches[item.index].info.disposition = item.disposition;
saveTheData('/analysis/apisaveconnectiondisposition', item);
}, function () {
});
};
}]);
matchesModalController.js
"use strict";
analysisApp.controller('matchesModalController', function ($scope, $rootScope, $uibModalInstance, itemData, saveData) {
$scope.itemData = itemData;
$scope.ok = function (item) {
$uibModalInstance.close(item);
};
$scope.cancel = function () {
$uibModalInstance.dismiss('cancel');
};
$scope.delink = function (item) {
BootstrapDialog.confirm({
title: 'WARNING',
message: '<p>Are you sure that you want to break the link between these items?</p>',
type: BootstrapDialog.TYPE_DANGER,
btnOKLabel: 'Break the link',
btnOKClass: 'btn-danger',
callback: function(result) {
if(result) {
$uibModalInstance.dismiss('delink');
saveTheData('/analysis/apidelink', item);
}else {
// cancel the operation
}
}
});
};
var saveTheData = function(url, item){
saveData
.postData(url, item)
.then(function(dataResponse){
$rootScope.$broadcast('connectionDispositionChanged', item);
})
};
});
I do not know what is wrong, ng-repeat is not
populating the information on my div, please look at the following
and advice where I have gone wrong
app.js
var mainApp = angular.module('mainApp', ["ngRoute", "ngResource"]);
mainApp.factory('EventListFactory',['$resource', EventListFactory]);
mainApp.controller('EventListCtrl', ['$scope','EventListFactory', EventListCtrl]);
var configFunction = function ($routeProvider) {
$routeProvider.
when('/Register', {
templateUrl: 'routesDemo/Register'
})
.when('/UpdateProfile', {
templateUrl: 'routesDemo/UpdateProfile'
})
.when('/Events', {
templateUrl: 'routesDemo/Events',
controller: EventListCtrl,
})
.when('/routeThree', {
templateUrl: 'routesDemo/three'
});
}
configFunction.$inject = ['$routeProvider'];
mainApp.config(configFunction);
EventListFactory.js
var EventListFactory = function ($resource, $location) {
var baseUrl = "";
if (window.location.hostname == 'localhost') {
baseUrl = "http://localhost:52182/api/Events/GetEvents/";
}
else
{
var deployAt = window.location.href.substring(0, window.location.href);
baseUrl = deployAt + "/api/Events/GetEvents";
}
var respone = $resource(baseUrl, null, { query: { method: 'GET', isArray: true, url: baseUrl }, get: { method: 'GET', url: baseUrl } });
console.log("api json at :" + baseUrl);
var records = respone.query();
console.log(records);
return records;
}
EventListController.js
var EventListCtrl = function ($scope, EventListFactory) {
$scope.Message = 'I work';
$scope.items = EventListFactory;
};
EventListCtrl.$inject = ['$scope'];
in the html:
<div id="listView" >
<h1 class="form-signin-heading">For real {{Message}}</h1>
<div ng-controller="EventListCtrl">
<p class="form-signin-heading">Populated Data</p>
<div ng-repeat="item in items ">
<span class="control-label">Heading : </span> {{item.Heading}}
<br/>
<span class="control-label">Event Date : </span> {{item.EventDate}}
<br/>
</div>
</div>
</div>
running the site:
api call from browser:
the code for ng-repeat is correct, but your items is an empty array so nothing gets displayed.
From the screenshots it appears that records in EventListFactory.js does not return an array but a promise.
In EventListController.js instead of
$scope.items = EventListFactory;
Try something like:
var promise = EventListFactory;
promise.then(function(data){
$scope.items = data;
})
I have a simple controller in AngularJS, and i would like it to have 2 different functions :
var app = angular.module('searchApp', []);
app.controller('searchCtrl', function($scope, $http, $log) {
//1st function
$scope.search = function() {
$http.post('server.php', { "data" : $scope.keywords})
.success(function(data, status) {
$scope.result = data;
})
};
//2nd function
$scope.tableClick = function() {
$log.log('Hello World!');
};
})
I think there's an issue somewhere in the syntax because this script works only when i remove the 2nd function.
When i use the script with the 2 functions (so, what i posted), i get {{ x }} for the following html elements :
<tr ng-repeat="x in result">
<td><a href="wwww.test.com" >{{ x }}</a></td>
Any clues ?
As I said in the comments, there's no echo 'Hello World!' in javascript. If you want to write that phrase on the DOM, then you have to use it as a simple expression. Just like:
$scope.helloWorld = 'Hello World!';
and then in the HTML you simply call it like {{helloWorld}}.
I'm seeing you're testing it with a function. In this case you should return the string 'Hello World!' like
$scope.helloWorld = function () {
return 'Hello World';
};
In the HTML:
{{ helloWorld() }}
In the case you want to simply "log" the Hello World! to the browser's console (which I doubt because you're not paying attention to JS errors): DO NOT USE console.log();. Use AngularJS' built-in service $log instead
A better code
Anyway, if I were you, I'd write that code differently. See
var app = angular.module('searchApp', []);
app.controller('searchCtrl', function ($scope, $http, $log) {
//1st function
$scope.search = function () {
$http.post('server.php', { "data" : $scope.keywords })
.then(function (resp) { //use then instead of success/error
return resp.data;
}, function inCaseOfErrors (err) { //named just for teaching purposes
$log.log(err);
});
};
//2nd function
$scope.tableClick = function () {
$log.log('Hello World!');
};
})
Please make sure that your $scope.result has the right values. Also note that echo doesn't exist in javascript.
In the code below, I took away the server-call and used hard-coded data, just to test:
var app = angular.module('searchApp', []);
app.controller('searchCtrl', function($scope, $http) {
$scope.result = ["apple", "orange", "raisin", "banana"];
//1st function
$scope.search = function() {
//$http.post('server.php', { "data" : $scope.keywords})
//.success(function(data, status) {
//$scope.result = data;
//})
};
//2nd function
$scope.tableClick = function(item) {
console.log("someone clicked the table! Row: " + item);
};
})
Html:
<table>
<tr ng-repeat="item in result">
<td data-ng-click="tableClick(item)">{{ item }}</td>
</tr>
</table>
I am using a loading spinner while loading a page.
App.controller('MailFolderController', ['$scope', '$http',function ($scope, $http){
$scope.loading = true;
$scope.allotmentStatus = [
{"value": "", "text": "All"},
{"value": "ALLOTTED", "text": "ALLOTTED"},
{"value": "UNALLOTTED", "text": "UNALLOTTED"}
];
$http.get(serverUrl).then(function (result) {
$scope.itemList = result;
});
$scope.changeItemList = function () {
$scope.loading = true;
$http.get(newServerUrl).then(function (result) {
$scope.itemList = result;
$scope.loading = false;
});
}
$scope.changeItemListAccordingToStatus = function (alotment) {
$scope.loading = true;
$http.get(newServerUrl+'?alotment='+alotment).then(function (result) {
$scope.itemList = result;
$scope.loading = false;
});
};
// Other functions
$scope.loading = false;
]}
And in view page :
<div ng-controller="ItemsController">
<button class="btn btn-primary" ng-click="changeItemList()"> Check New Items </button>
<select id="allotmentStatus" data-ng-model="allotment" ng-options="c.text for c in allotmentStatus" ng-change="changeItemListAccordingToStatus(allotment.value)"></select>
<table>
<img src="app/img/spinner.gif" ng-show="loading"/>
<tr ng-repeat="item in itemList">
<td>{{item.name}}</td>
<td>{{item.quentity}}</td>
<td>{{item.status}}<td>
</tr>
</table>
</div>
Loading spinner is working fine when page load first time, But when I click on button and change value of select tag the value of list are changing according to API call, But the loading spinner is not working. (ng-click is used in button click, and ng-change is used in Select tag)
Any suggestion will be appreciable . Thank you
Use another variable as we have discussed earlier because your variable may got reflected from another places.
App.controller('MailFolderController', ['$scope', '$http',function ($scope, $http){
//$scope.loading = true;
$scope.allotmentStatus = [
{"value": "", "text": "All"},
{"value": "ALLOTTED", "text": "ALLOTTED"},
{"value": "UNALLOTTED", "text": "UNALLOTTED"}
];
$http.get(serverUrl).then(function (result) {
$scope.itemList = result;
});
$scope.changeItemList = function () {
$scope.loadingSpinner = true;
$http.get(newServerUrl).then(function (result) {
$scope.itemList = result;
$scope.loadingSpinner = false;
});
}
$scope.changeItemListAccordingToStatus = function (alotment) {
$scope.loadingSpinner = true;
$http.get(newServerUrl+'?alotment='+alotment).then(function (result) {
$scope.itemList = result;
$scope.loadingSpinner = false;
});
};
// Other functions
$scope.loadingSpinner = false;
]}
HTML
<div ng-controller="ItemsController">
<button class="btn btn-primary" ng-click="changeItemList()"> Check New Items </button>
<select id="allotmentStatus" data-ng-model="allotment" ng-options="c.text for c in allotmentStatus" ng-change="changeItemListAccordingToStatus(allotment.value)"></select>
<table>
<img src="app/img/spinner.gif" ng-show="loadingSpinner"/>
<tr ng-repeat="item in itemList">
<td>{{item.name}}</td>
<td>{{item.quentity}}</td>
<td>{{item.status}}<td>
</tr>
</table>
</div>
I'm currently learning new MVC 6 and stucked completely with simple action - table data update on item selection change.The desired behaviour is to load questions that belong selected question block
I have angularJS factory:
(function () {
'use strict';
angular
.module('questionBlockApp')
.factory('questionBlockService', questionBlockService);
var questionBlockService = angular.module('questionBlockService', ['ngResource']);
questionBlockService.factory('Blocks', ['$resource',
function ($resource) {
return $resource('/api/blocks/', {}, {
query: { method: 'GET', params: {}, isArray: true }
});
}]);
questionBlockService.factory('Questions', ['$resource',
function ($resource) {
return $resource('/api/blocks/:blockId', {blockId : '#blockId'}, {
query: { method: 'GET', params: {}, isArray: true }
});
}]);
})();
Controller, which has refresh func (loadQuestions) built inside selection change function:
(function () {
'use strict';
angular
.module('questionBlockApp')
.controller('questionBlockController', questionBlockController);
//.controller('questionController', questionController);
questionBlockController.$inject = ['$scope', 'Blocks', 'Questions'];
//questionController.$inject = ['$scope', 'Questions'];
function questionBlockController($scope, Blocks, Questions) {
$scope.selectedBlock = 2;
if ($scope.Blocks == undefined | $scope.Blocks == null) {
$scope.Blocks = Blocks.query();
}
$scope.setSelected = function (blockId) {
$scope.selectedBlock = blockId;
$scope.loadQuestions();
}
$scope.loadQuestions = function () {
$scope.data = Questions.query({ blockId: $scope.selectedBlock });
$scope.data.$promise.then(function (data) {
$scope.Questions = data;
});
};
$scope.loadQuestions();
}
})();
And views:
View from which setSelected is called:
<table class="table table-striped table-condensed" ng-cloak ng-controller="questionBlockController">
<thead>
...
</thead>
<tbody>
<tr ng-repeat="block in Blocks" ng-click="setSelected(block.Id)" ng-class="{'selected': block.Id == selectedBlock}">
<td>{{block.Id}}</td>
<td>{{block.Name}}</td>
<td>{{block.Created}}</td>
</tr>
</tbody>
</table>
<table id="test" ng-controller="questionBlockController">
<thead>
<tr>
...
</tr>
</thead>
<tbody>
<tr ng-repeat="question in Questions">
<td>{{question.Id}}</td>
<td>{{question.Text}}</td>
<td>{{question.TimeLimit}}</td>
<td>{{question.Updated}}</td>
</tr>
</tbody>
</table>
When I click on different items in QuestionBlock table, $scope.Questions is updated properly, but the table does not reflect changes, as if no binding exists.
Okay, I am just a bit damaged.
There are two questionBlockController controllers defined, leading to intialization of different scopes => two $scope.Questions objects existence => refresh occured in Blocks scope, which was undesired behaviour.