AngularJS ng-init not working with ng-repeat - javascript

I've been trying to call passID() function when page initializes but the function still doesn't work.
The website works this way:
Page-A passes data to Controller-A
then to Service then to Controller-B then the function from Controller-B gets called by Page-B.
My guess is that my error is in Page-B since I've successfully passed the data of Page-A up to Controller-B but I'm not 100% sure.
In my Page-A, I've made a button calling the function of Controller-A using ng-Click
<button class="viewDetails" ng-click="passID([1,03,07])">test button</button>
Controller-A only gets data from Page-A
angular.module('handsetExplorerModule')
.controller("compareHandsetController", ['$scope','compareHandsetService','sharedData', function($scope, compareHandsetService, sharedData) {
$scope.passID = function(id){
var arrayID = [];
arrayID = id;
sharedData.set(arrayID);
};
}]);
Service gets my JSON and is my getter and setter
angular.module('handsetExplorerModule')
.factory('compareDetailsService', ['$http','$q', function($http, $q) {
return {
getHandsetList: function(){
return $http.get("./data/compareJSON.json");
}
};
}]);
angular.module('handsetExplorerModule')
.factory('sharedData', function() {
var savedData = {}
function set(data) {
savedData = data;
}
function get() {
return savedData;
}
return {
set: set,
get: get
}
});
Controller-B filters the JSON file to only get what I need (i used ID from Page-A to filter)
angular.module('handsetExplorerModule')
.controller("compareDetailsController", ['$scope','compareDetailsService','sharedData', function($scope, compareDetailsService, sharedData) {
$scope.data = {phones: []};
compareDetailsService.getHandsetList()
.then(
function(data){
$scope.data.phones = data.data;
},
function(error){
//todo: handle error
}
);
var getData = sharedData.get();
$scope.passID = function passID(){
var newData = [];
for(var i=0; i<$scope.data.phones.length; i++){
if($scope.data.phones[i].id == getData[0] || $scope.data.phones[i].id == getData[01] || $scope.data.phones[i].id == getData[02]){
newData.push($scope.data.phones[i]);
}
}
$scope.phoneContent = newData;
}
$scope.viewDetails = function(id){
alert(id);
}
}]);
Lastly, In my Page-B, I've called Controller-B function: <div ng-init="passID()">
to be used by ng-repeat of my Page-B:
<table id="Content" ng-repeat="x in phoneContent track by x.id">
<tr>
<td class="one">
<table>
<tr>
<td><img class="contImage" ng-src="{{x.image}}" ng-alt="{{x.name}}" /></td>
<td class="textAlign">{{x.name}} <button class="viewDetails" ng-click="viewDetails(x.id)">VIEW DETAILS</button></td>
</table>
</td>
<td class="two">{{x.size}}</td>
<td class="one">{{x.storage}}</td>
<td class="two">{{x.camera}}</td>
<td class="one">{{x.battery}}</td>
<td class="two">{{x.network}}</td>
<td class="one">{{x.sim}}</td>
</tr>
</table>

I don't know why you define arrayID.
To solve your problem try with sharedData.set = arrayID; instead of sharedData.set(arrayID);.
Hope it helps!

Related

AngularJS 1 - How to pass app.js list of values to controller.js

This is regarding Angular JS One, so I created a simple app in my plunkr.
What I did? , I created a factory called app.js and a myController.js.
The problem is the Get Method from controller.js, i dont know how to write it properly so it will pass the list of data to the html. Please check on methods getData(app.js)and Get(controller.js). What are the mistakes?
Note : Add and Edit are working fine using these three layers (app->controller->view) that i need.
PS: I tried nothing yet.
Thanks!!!
John
Below is my app.js or business
angular.module('myFirstApp',['ngRoute'])
.config(function($routeProvider){
$routeProvider
.when('/home',{templateUrl : 'home.html'})
.when('/people',{templateUrl : 'people.html'})
.when('/about',{templateUrl : 'about.html'})
.when('/contact',{templateUrl : 'contact.html'})
})
.factory('personFactory',function(){
function getData(){
$http.get('iphone.json').success(function(result){
return result;
}).error(function(error){
alert(error.error + "/" + error.statusCode);
});
}
function insertData(Name,Email,Password,Mobile){
//update data to database
var x = "Record added successfuly.";
return x;
}
function updateData(){
//update data to database
var x = "Record updated successfuly.";
return x;
}
return {
getData : getData,
insertData,
updateData
};
})
Below is my controller.js
angular.module('myFirstApp')
.controller('myController',function($scope,$http,personFactory){
$scope.Add = function(){
var x = personFactory.insertData($scope.Name,$scope.Email,$scope.Password,$scope.Mobile,$scope.result);
$scope.Message = x;
return $scope.Message;
}
$scope.Edit = function(){
var x = personFactory.updateData();
$scope.Message = x;
return $scope.Message;
}
$scope.Get = function(){
var x = personFactory.getData();
$scope.PeopleList = x;
return $scope.PeopleList;
}
})
Below is my view
<html>
<head>
<title></title>
<script src="app.js"></script>
</head>
<body>
<p>People</p>
<table ng-controller='myController'>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Model</th>
<th>Status</th>
<th>Purchased on</th>
</tr>
</thead>
<tr ng-repeat="values in PeopleList">
<td>{{values.name}}</td>
<td>{{values.email}}</td>
<td>{{values.model}}</td>
<td>{{values.status}}</td>
<td>{{values.purchasedate}}</td>
</tr>
</table>
</body>
</html>
The factory needs to return a JS Object that encapsulate all the functionalities, like this
// Data factory
app.factory("Data", function () {
return {
add: function () {
// add logic here
},
get: function () {
// get logic here
}
}
}
I guess you're having a little problem on the $http.get('iphone.json') within the factory. Maybe you should try to use a callback to handle that, like this:
app.js:
function getData(callback) {
$http.get('iphone.json').success(function(result){
callback(result);
}).error(function(error){
alert(error.error + "/" + error.statusCode);
});
}
controller.js:
$scope.Get = function(){
personFactory.getData(function(result) {
$scope.PeopleList = result;
});
}

Promises dont get resolved. Alasql doesnt import CSV

I cant figure out what the error is. I try to read out a CSV from my server and then to access the DateValues with an FUnction Called getZinsAnDatum.
The Chain begins in function:
$scope.calcZins = function database(ctrl, $scope) {....
I chained the results, reading out my CSV-Values via
getZinsAnDatum(dateee, fullDate)
works when I click twice or wait and click again. Guess it works, after clicking two times, because its load into the cache. The function itself returns a promise too, after i get Warning from this, pointing on the code lines from getZinsAnDatum(dateee, fullDate):
Warning: a promise was created in a handler at /localhost:8383/validations/js/index.js:269:17 but was not returned from it
Sorry if I miss fundamental concepts.
I guess the Promises arent chained right or its to much traffic, because for every Value i detect (about 200) it downloads the hole CSV? therefore I wanted to inject the CSV once in my Alasql database and work from there.
But putting it in doesnt seem to work. Therefore could you help me out maybe? Down my code HTML and javascript:
I spared out some functions and variables, all variables are given and defined.
Javascript:
/* global $scope, user,user.anpDat, user.zinsDiff, user.zinsJetz,user.zinsNext, user.nextAnpDat, user.AnzahlAnMonatenZwischenErsterAnpassungUndAktuellemDatum , user.Berechnung, ctrl.Berechnung, Promise, alasql*/
angular.module('MyApp', ['ngMaterial', 'ngMessages', 'material.svgAssetsCache']).controller('AppCtrl', function ($scope) {
this.fullDate = new Date("1999-12-20");
this.fullDate2 = new Date("2000-01-20");
this.fullDate3 = new Date("2010-03-19");
this.date = fullDate.toISOString().substring(0, 10);
this.date2 = fullDate2.toISOString().substring(0, 10);;
this.date3 = fullDate3.toISOString().substring(0, 10);;
var data = {};
var url = 'tests/fib.csv';
function getZinsAnDatum(dateee, fullDate) {
return new Promise(function (resolve, reject) {
alasql.promise('SELECT [1] FROM CSV("tests/fib.csv", {headers:false, }) WHERE [0] >=? AND [1]!="."', [dateee])
.then(function (data) {
var temp = data [1 ][1];
resolve(temp);
}).catch(function (err) {
console.log('Error:', err);
});
});
}
$scope.calcZins = function database(ctrl, $scope) {
this.mybase = new alasql.Database('mybase');
this.mybase.exec('CREATE TABLE one ');
this.mybase.exec('SELECT [0][1] INTO one FROM CSV("tests/fib.csv", {headers:false, })');
//this.mybase.exec('PRINT one'); //GIVES ERRORS, CANT READ UNDEFINED JSON Object
calcZins2(ctrl, $scope);
;
}
function calcZins2(ctrl, $scope) {
var user = new Object;
var anpassen = false;
user = angular.copy(ctrl);
user.Berechnung;
var Row;
getZinsAnDatum(user.date2, user.fullDate2).then(function (resu) {
// Code depending on result
var value = parseFloat(resu.replace(",", "."));
user.zinsJetz = value;
Row.zinsJetz=user.zinsJetz;
user.Berechnung.push(Row);
nextAbschnitt(user, ctrl, $scope);
}).catch(function () {
// An error occurred
});
function nextAbschnitt(user, ctrl, $scope) {
getZinsAnDatum(date3,fullDate3).then(function (resulte) {
// Code depending on result
var value = parseFloat(resulte.replace(",", "."));
user.zinsNext = value;
getZinsAnDatum(date, FullDate).then(function (result) {
// Code depending on result
var value3 = parseFloat(result.replace(",", "."));
user.zinsJetz = value3;
gO(user, ctrl, $scope);
}).catch(function () {
// An error occurred
});
}).catch(function () {
// An error occurred
});
}
}
function getMonthsDifference(date1, date2) {
var k = date1.getYear() * 12 + date1.getMonth();
console.log(k + "k")
var m2 = date2.getYear() * 12 + date2.getMonth();
console.log(m2 + "m2")
return (m2 - k + 1);
}
function gO(user, ctrl, $scope) {
var g = getMonthsDifference(user.date2 user.date3);
user.AnzahlAnMonatenZwischenErsterAnpassungUndAktuellemDatum = g;
var count = 0;
var promiseFor = Promise.method(function (condition, action, value) {
if (!condition(value))
return value;
return action(value).then(promiseFor.bind(null, condition, action));
});
promiseFor(function (count) {
return count < user.AnzahlAnMonatenZwischenErsterAnpassungUndAktuellemDatum;
}, function (count) {
// ctrl.Berechnung = user.Berechnung;
return getZinsAnDatum(date3, fullDate3 ).then(function (resulte) {
// DO STUFF
ctrl.done = true; // Shows THE HTML div via ng-Show
ctrl.Berechnung = user.Berechnung;
return ++count;
});
}, 0).then(function (user) {
});
}
});
HTML:
<tr> </tr>
<tr> </tr>
<tr> </tr>
<tr> </tr>
<tr> </tr>
<tr><td>Zinssatz nach richtiger Anpassung:</td><td> {{ctrl.zinssatzKorrekt}}</td></tr>
<tr><td>Aktueller Zinssatz der Bank</td><td>{{ctrl.zinssatzAktuell}}</td></tr>
<tr><td>Differenz: </td><td>{{ctrl.zinssatzAktuell-ctrl.zinssatzKorrekt}}</td></tr>
<tr> </tr>
<tr> </tr>
<tr> </tr>
<tr> </tr>
<tr> </tr>
<tr> </tr>
<tr> </tr>
<tr> </tr> <tr> </tr>
<tr>
<td>FIBOR/EURIBOR-Stichtag</td><td>maßgeblicher FIBOR/EURIBOR in %</td><td>FIBOR/EURIBOR-
Veränderung</td> <td>Veränderung
kumuliert</td> <td>Anpassung</td> <td>gebotene
Anpassung</td> <td>Zinssatz korrekt</td></tr>
<tr ng-class="Texttype" ng-repeat="row in ctrl.Berechnung track by $index">
<td> {{row.anpDat}}</td><td>{{row.zinsJetz}} </td><td>{{row.zinsDiff}} </td> <td>{{row.veranderungKummuliert}} </td> <td>{{row.anpassen}} </td> <td>{{row.geboteneAnpassung}} </td> <td>{{row.zinssatzKorrekt}} </td></tr>
</table>

Use filter to filter result in angularJS

Hi I have a table with data in it,what I what is to filter the result so that if a table row have a datetime that is not current like today's date that specific row must not be shown or just change the background-color of it. Here is what I have tried but it doesn't work. Even if it's not filter what-else can I use? Basically the first row must appear
<table class="table table-striped table-bordered table-hover table-fixedheader">
<thead>
<tr>
<th>KomaxShortname</th>
<th>OriginalFileName</th>
<th>OriginalPath</th>
<th>OriginalModifiedDateTime</th>
<th>UpLoadedDateTime</th>
<th>AgeInMinutes</th>
<th>FileLength</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="latestwpcsfiles in Model.WpcsFiles | filter:{OriginalModifiedDateTime:'!CurrentDateTime'}">
<td>{{latestwpcsfiles.KomaxShortname}}</td>
<td>{{latestwpcsfiles.OriginalFileName}}</td>
<td>{{latestwpcsfiles.OriginalPath}}</td>
<td>{{latestwpcsfiles.OriginalModifiedDateTime}}</td>
<td>{{latestwpcsfiles.UpoadedDateTime}}</td>
<td>{{latestwpcsfiles.AgeInMinutes}}</td>
<td>{{latestwpcsfiles.FileLength}}</td>
</tr>
</tbody>
</table>
JS
function Model($http) {
var self = this;
self.$http = $http;
self.WpcsFiles = [];
self.GetLatestWpcsFiles = function () {
return ngHesto.Ajax.Get(self.$http
, {
url: 'http://10.19.13.68/GetLatestWpcsFiles/Default.aspx'
, success: function (data) {
self.WpcsFiles = data.data;
console.log(self.WpcsFiles);
}
});
}
self.GetLatestWpcsFiles();
}
ngAppModule.controller('LatestWpcsFilesController', ['$scope', '$http', function ($scope, $http) {
$scope.Model = new Model($http);
}]);
The easiest way imo would be to create a custom filter like this:
function(items, date) {
var result = [];
if (items != null) {
for (var i = 0; i < items.length; i++;){
var item = items[i];
if (item.OriginalModifiedDateTime.getDate() == date.getDate())
result.push(item);
}
}
return result;
}

Apply ng-class to array of items in angularjs

I am trying to highlight multiple row select functionality, so that when a user click's on a row it highlight the row and when it again select that row it un-highlight that. But the problem I am facing is how to give array of items to ng-class.
Here is my code.
<tr ng-click="selectRow(1)" ng-class="{row_selected: ArrayOfItems}" class="ng-scope odd">
<td class="">
test
</td>
</tr>
And in my controller
$scope.selectedArray = [];
$scope.selectRow = function(id) {
if($scope.selectedArray.indexOf(id) == -1) {
$scope.selectedArray.push(id);
}else {
$scope.selectedArray.splice($scope.selectedArray.indexOf(id),1);
}
});
So what I am doing in controller is on clicking a row it push the id's in an array and on clicking the same row it pops out that id from array.
Any help ?
First check whether the row is selected or not
<tr ng-click="selectRow(1)" ng-class="{row_selected: isRowSelected(1)}" class="ng-scope odd">
<td class="">
test
</td>
</tr>
Add the isRowSelected to controller:
$scope.selectedArray = [];
$scope.isRowSelected = function(id) {
$scope.selectedArray.indexOf(id) != -1
}
$scope.selectRow = function(id) {
if($scope.selectedArray.indexOf(id) == -1) {
$scope.selectedArray.push(id);
}else {
$scope.selectedArray.splice($scope.selectedArray.indexOf(id),1);
}
});
More proper setup would be with in use of 'ng-repeat'. See the working code at:
JSFiddle
HTML:
<div ng-controller="MyController">
<table>
<tr ng-repeat="item in items" ng-click="selectRow(item)" ng-class="{row_selected: isSelected(item)}">
<td>
<a id="{{item}}">test {{item}}</a>
</td>
</tr>
</table>
</div>
JS/AngularJS:
var myApp = angular.module('myApp', []);
myApp.controller('MyController', ['$scope', function ($scope) {
$scope.items = [1,2,3,4,5];
$scope.selectedArray = [];
$scope.selectRow = function (id) {
if($scope.selectedArray.indexOf(id) == -1) {
$scope.selectedArray.push(id);
}else {
$scope.selectedArray.splice($scope.selectedArray.indexOf(id),1);
}
};
$scope.isSelected = function (id) {
if( $scope.selectedArray.indexOf(id) > -1){
return true;
}
return false;
};
}]);

Knockout.js use foreach to display object properties

I have this Viewmodel to load the users and their list of Socialgraphs from WCF services. The users appear correct but no socialgraph entry appears. I have checked the service and json returned and all seems ok.
Should I change my Models to sth different or is it the way I'm loading stuff in the ViewModel? thanks
$(document).ready(function () {
var viewModel = {
users: ko.observableArray([]),
loadUsers: function () {
OData.read("Service_UserProfile/", function (data) {
viewModel.users.removeAll();
$.each(data.results, function (index, item) {
var socialgraphs = viewModel.loadSocialGraph();
var user = new UserProfileModel(item, socialgraphs);
viewModel.users.push(user);
});
});
},
loadSocialGraph: function () {
var result = new Array();
// user id will be loaded dynamically in later steps
OData.read("/Service_UserProfile(1)/Socialgraph/", function (data) {
$.each(data.results, function (index, item) {
result.push(new SocialGraph(item));
});
});
return result;
}
};
ko.applyBindings(viewModel);
viewModel.loadUsers();
});
The Model
function UserProfileModel(item,socialgraphs) {
this.Id = ko.observable(item.Id),
this.Nickname = ko.observable(item.Nickname),
this.socialgraphs = ko.observableArray(socialgraphs)
};
function SocialGraph(item) {
this.Id = ko.observable(item.Id),
this.StartTime = ko.observable(item.StartTime),
this.Latitude = ko.observable(item.Latitude),
this.Longitude = ko.observable(item.Longitude)
};
The View
<table>
<thead>
<tr>
<th>User ID</th>
<th>Nickname
</th>
<th>Social Graph
</th>
</tr>
</thead>
<tbody data-bind="foreach: users">
<tr>
<td data-bind="text: Id"></td>
<td data-bind="text: Nickname"></td>
<td>
<ul data-bind="foreach: socialgraphs">
<li data-bind="text: Id"></li>
<li data-bind="dateString: StartTime"></li>
<li data-bind="text: Latitude"></li>
<li data-bind="text: Longitude"></li>
</ul>
</td>
</tr>
</tbody>
</table>
You should change:
loadSocialGraph: function () {
var result = ko.observableArray();
// user id will be loaded dynamically in later steps
OData.read("/Service_UserProfile(1)/Socialgraph/", function (data) {
$.each(data.results, function (index, item) {
result.push(new SocialGraph(item));
});
});
return result;
}
and
function UserProfileModel(item,socialgraphs) {
this.Id = ko.observable(item.Id),
this.Nickname = ko.observable(item.Nickname),
this.socialgraphs = socialgraphs
};
Why:
At the line this.socialgraphs = ko.observableArray(socialgraphs)
socialgraphs in the right part is []. Only after some time interval it
will be filled with values. And because of it is not observable array,
knockout won't notice that some items were pushed in it. I.e. it will stay empty.

Categories

Resources