Watch change on property of complex structure - javascript

here is my story. I've a view that shows shifts per user per day.
My model is quite complicated and looks moreless like this:
planner = {
//...
entries: {
'2016-03-01': {
'user1': {
date: '2016-03-01',
id: 1,
user: Object {}
shift: Object {}
},
'user2': {
//...
}
},
'2016-03-02': {
//...
}
}
}
In controller i create a range of dates, array of users and iterate over my structure to create a cell for each user/day.
For each of my cells i have a directive with extension that on click, the controller setShift(cell, shift) is called, where i update the cell with new shift and do PUT.
But the problem is that, despite i set a new shift on that cell, the DOM is not changed.
I tried with $watch('planner', fn, true) and i see that the planner object has a new shift set for the cell but at the DOM, nothing changed.
I have to call loadAll that sets a newly fetched planner to the scope to see the DOM updates.
If you have a better idea, i'm waiting for it!
Cheers
EDIT: here goes controller
'use strict';
angular.module('myapp')
.controller('PlannerController', function ($scope, $state, Planner, ShiftEntry) {
$scope.mom = moment();
$scope.dateRange = [];
$scope.planner = undefined;
$scope.loadAll = function(year, month) {
Planner.get({year: year, month: month+1}, function(result) {
$scope.planner = result;
});
};
$scope.$watchGroup(['mom.year()', 'mom.month()'], function(newValues, oldValues, scope) {
$scope.loadAll(newValues[0], newValues[1]);
$scope.dateRange = _.chain(
_.range(1, $scope.mom.clone().endOf('month').date()+1))
.map(function(d) {
return moment().year(newValues[0])
.month(newValues[1])
.date(d);
})
.value();
});
$scope.switchMonth = function(dir) {
//...
};
$scope.getColor = function(day, user) {
//...
};
$scope.sum = function(day, shift) {
//...
};
$scope.getEntry = function(day, user) {
return $scope.planner.entries[day.format('YYYY-MM-DD')][user.login];
};
$scope.setShift = function(shiftEntry, shift) {
shiftEntry.shift = shift;
ShiftEntry.update(shiftEntry);
// when line below is uncommented everything works and is updated
//$scope.loadAll($scope.mom.year(), $scope.mom.month());
};
$scope.$watch('planner', function(newVal) {
console.log(newVal);
}, true );
});
and template
<div class="shiftChart">
<div class="users pull-left">
<div class="lbl">Employee</div>
<div class="user clearfix" ng-repeat="user in planner.users">
<img ng-src="assets/images/avatars/{{user.login}}.jpg" alt="{{user.login}}">
<div class="name">{{user.firstName}} {{user.lastName}}</div>
<div class="extra">{{user.login}}</div>
</div>
</div>
<div class="dates-wrapper">
<div class="dates pull-left" ng-repeat="day in dateRange" ng-class="{'weekend' : day.isWeekendDay(), 'today' : day.isSame(moment(), 'day')}">
<div class="lbl">{{day.format('DD')}}</div>
<div class="entries">
<div class="entry" ng-repeat="user in planner.users">
<div class="shift" style="background-color: ${{getColor(day, user)}}" planner-shift-changer></div>
</div>
</div>
</div>
</div>
</div>

Related

Problem with Vue.js when it needs to fetch an url (wp-api) on a keyup event

Here's my issue. I created a tool with vue.js and the WordPress API to search through the search endpoints for any keyword and display the result. So far so good, everything is working, except for a bug that I spotted.
Here's the deal:
const websiteurl = 'https://www.aaps.ca'; //yourwebsite or anything really
var vm = new Vue({
el: '#blog-page',
data: {
noData: false,
blogs: [],
page: 0,
search: '',
totalPagesFetch: "",
pageAmp: "&page=",
apiURL: `${websiteurl}/wp-json/wp/v2/posts?per_page=6`,
searchbyid: `${websiteurl}/wp-json/wp/v2/posts?per_page=6&include=`,
searchUrl: `${websiteurl}/wp-json/wp/v2/search?subtype=post&per_page=6&search=`,
},
created: function () {
this.fetchblogs();
},
methods: {
fetchblogs: function () {
let self = this;
self.page = 1;
let url = self.apiURL;
fetch(url)
.then(response => response.json())
.then(data => vm.blogs = data);
},
searchonurl: function () {
let ampersand = "&page=";
searchPagination(1, this, ampersand);
},
}
});
function searchPagination(page, vm, pagen) {
let self = vm;
let searchword = self.search.toLowerCase();
let newsearchbyid = self.searchbyid;
let url;
self.page = page;
url = self.searchUrl + searchword + pagen + self.page;
self.mycat = 'init';
fetch(url)
.then(response => {
self.totalPagesFetch = response.headers.get("X-WP-TotalPages");
return response.json();
})
.then(data => {
let newid = [];
data.forEach(function (item, index) {
newid.push( item.id );
});
if (newid.length == 0) {
return newsearchbyid + '0';
} else {
return newsearchbyid + newid;
}
})
.then(response2 => {
return fetch(response2)
})
.then(function(data2) {
return data2.json();
})
.then(function(response3) {
console.log(response3)
if (response3.length == 0) {
vm.noData = true;
vm.blogs = response3;
} else {
vm.noData = false;
vm.blogs = response3;
}
})
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap#4.3.1/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div class="lazyblock-blogs testblog" id="blog-page">
<div class="container">
<div class="row controls">
<div class="col-md-12">
<div class="search-blog">
<img height="13" src="" alt="search">
<input id="sb" type="text" v-model="search" #keyup="searchonurl" placeholder="search">
</div>
</div>
</div>
<div class="row">
<div class="col-md-4" v-for="(b, index) in blogs">
<div class="h-100 box" v-cloak>
<img width="100%" v-bind:src=b.featured_image_url>
<a v-bind:href="b.link">
<h3 v-html=b.title.rendered></h3>
</a>
<div v-html=b.excerpt.rendered></div>
<p class="read-more"><a v-bind:href="b.link">read more</a></p>
</div>
</div>
<div class="no-data" v-if="noData">
<div class="h-100">
No post
</div>
</div>
</div>
</div>
</div>
I'm using a keyup event which is causing me some problems because it works, but in same cases, for example, if the user is very fast to type characters and then suddenly he wants to delete the word and start again, the response for the API has some sort of lag.
The problem is that I guess that the Vue framework is very responsive (I create a variable call search that will update immediately) but the API call in the network is not (please check my image here):
This first image appears if I type lll very fast, the third result will return nothing so it is an empty array, but if I will delete it immediately, it will return an url like that: https://www.aaps.ca//wp-json/wp/v2/search?subtype=post&per_page=6&search=&page=1 which in turn should return 6 results (as a default status).
The problem is that the network request won't return the last request but it gets crazy, it flashs and most of the time it returns the previous request (it is also very slow).
Is that a way to fix that?
I tried the delay function:
function sleeper(ms) {
return function(x) {
return new Promise(resolve => setTimeout(() => resolve(x), ms));
};
}
and then I put before the then function:
.then(sleeper(1000))
but the result is the same, delayed by one second (for example)
Any thought?
This is the case for debounced function. Any existing implementation can be used, e.g. Lodash debounce. It needs to be declared once per component instance, i.e. in some lifecycle hook.
That searchPagination accepts this as an argument means that something went wrong with its signature. Since it operates on component instance, it can be just a method and receive correct this context:
methods: {
searchPagination(page, pagen) {
var vm = this;
...
},
_rawsearchonurl() {
let ampersand = "&page=";
this.searchPagination(1, ampersand);
}
},
created() {
this.searchonurl = debounce(this._rawsearchonurl, 500);
...
}
You could use debounce, no call will leave until the user stop typing in the amount of time you chose
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
clearTimeout(timeout);
timeout = setTimeout(function() {
timeout = null;
if (!immediate) func.apply(context, args);
}, wait);
if (immediate && !timeout) func.apply(context, args);
};
}
// in your "methods" (I put 1000ms of delay) :
searchonurl: function () {
let ampersand = "&page=";
debounce(searchPagination, 1000)(1, this, ampersand);
}
One of best ways is to use Debounce which is mentioned in this topic
Or use a function and combine it with watch. Follow these lines:
In mounted or created make an interval with any peroid you like (300 etc.) define a variable in data() and name it something like searched_value. In interval function check the value of your input and saerch_value, if they were not equal (===) then replace search_value with input value. Now you have to watch search_value. When it changed you call your api.
I use this method and works fine for me. Also it`s managable and everything is in your hand to config and modify.
===== UPDATE: =====
A simple code to do what I said above
<template>
<div>
<input type="search" v-model="search_key">
</div> </template>
<script> export default {
name: "SearchByApi",
data() {
return {
search_key: null,
searched_item: null,
loading: false,
debounceTime: 300,
}
},
created() {
this.checkTime()
const self = this
setInterval(function() {
self.checkTime()
}, this.debounceTime);
},
watch: {
searched_item() {
this.loadApi()
}
},
methods: {
checkTime() {
if (this.searched_item !== this.search_key && !this.loading) {
this.searched_item = this.search_key
}
},
loadApi() {
if (!this.loading && this.searched_item?.length > 0) {
this.loading = true
const api_url = 'http://api.yourdomain.com'
axios(api_url, {search: this.searched_item}).then(res => {
// whatever you want to do when SUCCESS
}).catch(err => {
// whatever you want to do when ERROR
}).then(res => {
this.loading = false
})
}
}
}
}
</script>

ng-click(parameters) open a popup window with dropdown,then selected item and parameters sent to the service

I'm new to Angular-js. I'm using JSP for front end and passing values from UI to controller.Now I need to open a new popup list where user can select an option, then pass all parameters to service ..
ng-click="rewardRetry(singleWinner)"
controller --->
$scope.retryRewardDTO = {
"mobile_number" : null,
"draw_id" : 0,
"lottery_ticket_id" : 0,
"prize" : 0,
"reward_method" :null
};
(mobile_number,draw_id,lottery_ticket_id,prize) I can assign like this
$scope.rewardRetry = rewardRetry;
function rewardRetry(rewardRetryDTO) {
$scope.retryRewardDTO.draw_id=rewardRetryDTO.draw_id;
$scope.retryRewardDTO.lottery_ticket_id=rewardRetryDTO.lottery_ticket_id;
$scope.retryRewardDTO.prize=rewardRetryDTO.prize;
$scope.retryRewardDTO.mobile_number=rewardRetryDTO.mobile_number;
//$scope.retryRewardDTO.reward_method=rewardRetryDTO.reward_method;
}
But here retryRewardDTO.reward_method -->user should be select in popup option. (wallet,m_cash,reload,,, ....etc)
calling to service
winnerService.winnerService.rewardRetry(
$scope.retryRewardDTO,
function(data, headers) {
winnerSearch();
}, function() {
});
I'm trying do something like below link.but couldn't get a proper output.please some helps to me...
visit :AngularJS Modal Popup
Finally I found the answer and here implemented new rewardService
$scope.rewardRetry = rewardRetry;
function rewardRetry(rewardRetryDTO) {
$scope.retryRewardDTO.draw_id=rewardRetryDTO.draw_id;
$scope.retryRewardDTO.lottery_ticket_id=rewardRetryDTO.lottery_ticket_id;
$scope.retryRewardDTO.prize=rewardRetryDTO.prize;
$scope.retryRewardDTO.mobile_number=rewardRetryDTO.mobile_number;
//$scope.retryRewardDTO.reward_method=rewardRetryDTO.reward_method;
var modalOptions = {
bodyText : 'Are you sure you want to retry '+$scope.retryRewardDTO.prize+'/= reward for 0'+ $scope.retryRewardDTO.mobile_number+' ? Please select a reward method first and confirm'
};
rewardService.showModal({}, modalOptions).then(
function(result) {
$scope.retryRewardDTO.reward_method = result;
$('#retry-'+rewardRetryDTO.draw_id+'-'+rewardRetryDTO.lottery_ticket_id).hide();
$timeout(function() {
winnerService.winnerService.rewardRetry(
$scope.retryRewardDTO,
function(data, headers) {
winnerSearch();
}, function() {
});
});
});
}
;
My reward_option.jsp file
<%# taglib prefix="sec"
uri="http://www.springframework.org/security/tags"%>
<div class="option">
<div class="pull-right"></div>
<div>Copyright © Lucky889 2016</div>
<input type="hidden" value="<sec:authentication property="principal.userType" />" id="user_type" />
<input type="hidden" value="<sec:authentication property="principal.operator" />" id="user_operator" />
</div>
<script type="text/ng-template" id="rewardModalContent.html">
<div class="modal-header">
<h3>{{modalOptions.headerText}}</h3>
</div>
<div class="modal-body">
<p>{{modalOptions.bodyText}}</p>
<div class="modal-body">
<%-- <p ng-repeat="(key,singleReward) in modalOptions.rewardList">{{key}}----{{singleReward}}</p> --%>
<div class="form-group">
<label class="control-label" for="reward">Reward
Method</label><select name="reward" id="reward"
ng-model="reward_method" class="form-control">
<option ng-repeat="(key,singleReward) in modalOptions.rewardList"
value="{{key}}">{{singleReward}}</option>
</select>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-primary"
data-ng-click="modalOptions.confirm(reward_method)">{{modalOptions.actionButtonText}}</button>
<button type="button" class="btn"
data-ng-click="modalOptions.cancel()">{{modalOptions.closeButtonText}}</button>
</div>
</script>
Here is my rewardService
angular.module("zmessengerRewardApp.service", []).service(
'rewardService',
function(toastr, $uibModal, $log) {
var showHeaderErrorMessage = function(header) {
toastr.clear();
toastr.error(header['lms-message'],
header['lms-root-cause-message']);
};
var showHeaderSuccessMessage = function(header) {
toastr.clear();
toastr.success(header['lms-message'],
header['lms-root-cause-message']);
};
var modalDefaults = {
backdrop : true,
keyboard : true,
modalFade : true,
templateUrl : 'rewardModalContent.html'
};
var modalOptions = {
closeButtonText : 'Cancel',
actionButtonText : 'Confirm',
headerText : 'Confirmation',
bodyText : 'Perform this action?',
rewardList : {reload:'Auto Reload',manual_reload:'Manual Reload',ez_cash:'Ezcash',mcash:'MCash',wallet:'Wallet',bank:'Bank Transfer'}
};
function showModal(customModalDefaults, customModalOptions) {
if (!customModalDefaults)
customModalDefaults = {};
customModalDefaults.backdrop = 'static';
return show(customModalDefaults, customModalOptions);
};
function show(customModalDefaults, customModalOptions) {
// Create temp objects to work with since we're in a singleton
// service
var tempModalDefaults = {};
var tempModalOptions = {};
// Map angular-ui modal custom defaults to modal defaults
// defined in service
angular.extend(tempModalDefaults, modalDefaults,
customModalDefaults);
// Map modal.html $scope custom properties to defaults defined
// in service
angular.extend(tempModalOptions, modalOptions,
customModalOptions);
if (!tempModalDefaults.controller) {
tempModalDefaults.controller = function($scope,
$uibModalInstance) {
$scope.modalOptions = tempModalOptions;
$scope.modalOptions.confirm = function(result) {
$uibModalInstance.close(result);
};
$scope.modalOptions.cancel = function(result) {
$uibModalInstance.dismiss('cancel');
};
}
}
return $uibModal.open(tempModalDefaults).result;
};
return {
showHeaderErrorMessage : showHeaderErrorMessage,
showHeaderSuccessMessage : showHeaderSuccessMessage,
showModal : showModal,
};
});

Item can't be moved after destination list gone empty once, how can I fix it?

See the plnkr http://plnkr.co/edit/atoDX2TqZT654dEicqeS?p=preview
How to move item from the list to the another empty list. Currently an item can't be moved once the destination list gone empty... How I can fix this for my application?
Here is the code sniped on tags for my application:
<div class="row">
<div class="span4 offset2" style="overflow-y:auto; height:150px;">
<ul ui-sortable="sortableOptions" ng-model="allDiagnosisFromDb" id="sourceList" ng-class="{'minimalList':sourceEmpty()}" class="connector">
<li class="alert alert-danger nomargin" ng-repeat="item in allDiagnosisFromDb">{{item.Name}}</li>
</ul>
</div>
<div class="span4" style="overflow-y:auto; height:150px; background-color:lightgray">
<ul ui-sortable="sortableOptions" id="targetList" ng-model="model" ng-class="{'minimalList':sourceEmpty()}" class="connector">
<li class="alert alert-info nomargin" ng-repeat="item in model">{{item.Name}}</li>
</ul>
</div>
</div>
code on angularjs controller:
function loadAllDiagnosis() {
$scope.allDiagnosisFromDb = [];
diagnosisPreferanceService.getAllDiagnosis()
.success(function (data) {
$scope.allDiagnosisFromDb = data;
})
.error(function (xhr) {
alert('error');
});
}
// init
$scope.model = [
{
"Id": 23,
"Name": "First tem."
}
];
$scope.sortableOptions = {
connectWith: '.connector'
}
// watch, use 'true' to also receive updates when values
// change, instead of just the reference
$scope.$watch("model", function (Name) {
console.log("Model: " + Name.map(function (e) { return e.Id }).join(','));
}, true);
// watch, use 'true' to also receive updates when values
// change, instead of just the reference
$scope.$watch("allDiagnosisFromDb", function (Name) {
console.log("allDiagnosisFromDb: " + Name.map(function (e) { return e.Id }).join(','));
}, true);
$scope.sourceEmpty = function () {
return $scope.allDiagnosisFromDb.length == 0;
}
$scope.modelEmpty = function () {
return $scope.model.length == 0;
}
Thanks in advance,,,,,,,,,:)
You can refer the below link exactly how you want it to be.
http://marceljuenemann.github.io/angular-drag-and-drop-lists/demo/#/simple
angular.module("demo").controller("SimpleDemoController", function($scope) {
$scope.models = {
selected: null,
lists: {"A": [], "B": []}
};
// Generate initial model
for (var i = 1; i <= 3; ++i) {
$scope.models.lists.A.push({label: "Item A" + i});
$scope.models.lists.B.push({label: "Item B" + i});
}
// Model to JSON for demo purpose
$scope.$watch('models', function(model) {
$scope.modelAsJson = angular.toJson(model, true);
}, true);
});

angularJs, I'm not succeeding set view refresh after data get from ajax call

I've searched a lot before answer this question and couldn'y find any solution working for me.
I've started studying angular and I've been able to create a simple page with an ng-repeat that iter an object.
The next step I want to achieve is to update this object from an AJAX call to an API. The problem is that I'm not able to do this.
It seems to me that the problem is the function inside the controller: is not able to edit an attribute of the same controller:
app.controller('StoreController', [ '$http', 'ajaxFactory',
function($http, ajaxFactory) {
this.products = products;
this.getProducts = function() {
/* this works and empty the object AND the view on the click */
this.products = [];
ajaxFactory.getFamily2().then(function(data) {
/*
* this DOES NOT works, DOES NOT empty the object NOR the
* view on the click
*/
/*
* i'm sure the AJAX call is working, i can see the result
* and also alert his content
*/
this.products = data;
});
};
} ]);
Thanks in advance
FULL CODE:
Html:
<div ng-app="catalogo">
<div ng-controller="StoreController as store">
<!-- *** Store Header *** -->
<header class="text-center">
<h3>– an Angular catalogue –</h3>
</header>
<!-- *** Products Container *** -->
<div class="container" ng-controller="TotalPriceController as total">
<div class="row">
<!-- Product Container -->
<div class="col col-xs-4"
ng-repeat="(key,product) in store.products"
ng-class="{ hero: key%2 === 0 }">
<div class="row">
<product-title></product-title>
</div>
<div class="row">
<!-- Image Gallery -->
<product-gallery></product-gallery>
</div>
<div class="row">
<!-- Product Tabs -->
<product-calculate></product-calculate>
</div>
<div class="row">
<!-- Product Tabs -->
<product-tabs></product-tabs>
</div>
</div>
</div>
<div class="row">
<button ng-click="store.getProducts()">Kliq Here!</button>
<product-total></product-total>
</div>
</div>
</div>
JS:
(function() {
var app = angular.module('catalogo', [ 'store-directives' ]);
app.factory('ajaxFactory', function($http) {
var factory = {};
factory.getFamily2 = function() {
return $http.get("http://apigility-ds.gsanet.it/rpc").then(
function(result) {
return result.data;
});
}
return factory;
});
app.controller('TotalPriceController', function() {
this.totalPrice = 0;
this.calculateTotalPrice = function() {
this.totalPrice = 0;
for ( var x in products) {
var product = products[x];
if (typeof (product.num) !== 'undefined') {
this.totalPrice += (product.price * product.num);
}
}
};
});
app.config(function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
});
app.controller('StoreController', [ '$http', 'ajaxFactory',
function($http, ajaxFactory) {
this.products = products;
this.getProducts = function() {
this.products = [];
ajaxFactory.getFamily2().then(function(data) {
this.products = data;
});
};
} ]);
app.controller('ReviewController', function() {
this.review = {};
this.addReview = function(product) {
product.reviews.push(this.review);
this.review = {};
};
});
var products = [ {
name : 'Ballons',
price : 7.99,
description : "A lot of colored ballons",
images : [ "../img/balloons.jpg", "../img/balloons2.jpg" ],
specs : {
number : 10,
color : 'various'
},
reviews : []
}, {
name : 'Cards',
price : 3.99,
description : "wonderful set of cards.",
images : [ "../img/cards.jpg", "../img/cards2.jpg" ],
specs : {
type : 'poker deck',
cards : 52
},
reviews : []
}, {
name : 'Watch',
price : 159.99,
description : "An awesome watch, make you so cool.",
images : [ "../img/watchmaker.jpg", "../img/watchmaker2.jpg" ],
specs : {
color : 'black',
year : '2014',
brand : 'SWATCH'
},
reviews : []
} ];
})();
You are having invalid reference to this.products from closure(It doesn't refere to this.products declared outside the getProducts function). You can correct it like this
app.controller('StoreController', [ '$http', 'ajaxFactory',
function($http, ajaxFactory) {
var controller = this;
controller.products = products;
controller.getProducts = function() {
/* this works and empty the object AND the view on the click */
controller.products = [];
ajaxFactory.getFamily2().then(function(data) {
/*
* this DOES NOT works, DOES NOT empty the object NOR the
* view on the click
*/
/*
* i'm sure the AJAX call is working, i can see the result
* and also alert his content
*/
controller.products = data;
});
};
} ]);
Between you can also have a look on angular services to make your code more robust and easier to test.

Assign ng-model to checkbox if some value == anothervalue

I have a User object in Angular controller. I also have an array of Account objects with respective ID for each.
In User I have a field "default_account" where I want to put ID of a default account. So, user can have a lot of accounts but only one of them can be default. When I go to Account options, I have a checkbox there which is responsible for setting/unsetting the account as default.
Now I want to set checkbox on/off depending on its being default for the user. And I also need to respectively change default_account field inside User object on checkbox change. It puzzles me quite much how I can do it.
Any advice is appreciated!
Very approximate (didn't text that):
html:
<div ng-repeat="account in accounts">
<input type="checkbox" ng-checked="account == user.default_acount"
ng-click="SelectAssDefault(account )" />
</div>
js:
function MyCtrl($scope) {
$scope.user = { name: 'user', default_acount: null};
$scope.accounts = [{ }, { }, ...];
$scope.SelectAssDefault = function (account) {
$scope.user.default_acount = account;
};
}
EDIT: a working example: http://jsfiddle.net/ev62U/120/
If you want to set a checkbox to true based on a variable, you can set ng-checked="variable" within the input tag.
If the variable is true the box will be checked. If it's false it won't. Alternatively, an expression will also work e.g. ng-checked="1===1" will evaluate to true.
If you want to alter something else based on user clicking on the checkbox, set ng-click="someCtrlFunction()" within the input tag. This will call a function in your controller. You can look up the value of the checkbox from your controller if you've bound to it.
Here's a fiddle: http://jsfiddle.net/E8LBV/10/ and here's the code:
HTML
<div ng-app="App">
<div ng-controller="AppCtrl">
<ul>
<li ng-repeat="user in users">{{user.name}}
<ul>
<li ng-repeat="account in user.accounts">
<input type="checkbox" ng-model="checked" ng-checked="account == user.default" ng-click="changeDefault(user.id,account,checked)">{{account}}</input>
</li>
<ul/>
</li>
</ul>
</div>
</div>
JS
var app = angular.module('App', []);
app.service('Users', function () {
var Users = {};
Users.data = [{
'id': 1,
'name': 'jon',
'default': null
}, {
'id': 2,
'name': 'pete',
'default': null
}];
return Users;
});
app.service('Accounts', function () {
var Accounts = {};
Accounts.data = [{
'user': 1,
'ac': 123456
}, {
'user': 2,
'ac': 456832
}, {
'user': 2,
'ac': 345632
}, {
'user': 1,
'ac': 677456
}];
return Accounts;
});
app.controller('AppCtrl', function ($scope, Users, Accounts) {
$scope.users = Users.data;
//attach accounts to user
for (i = 0; i < $scope.users.length; i++) {
$scope.users[i].accounts = [];
for (ii = 0; ii < Accounts.data.length; ii++) {
if (Accounts.data[ii].user == $scope.users[i].id) {
$scope.users[i].accounts.push(Accounts.data[ii].ac);
}
}
}
//function to change the default account for the user
$scope.changeDefault = function (id, account, checked) {
if (!checked) {
return;
}
for (i = 0; i < $scope.users.length; i++) {
if ($scope.users[i].id == id) {
$scope.users[i].
default = account;
}
}
}
});
Here is my solution that perfectly worked for me!
<tbody ng-repeat="account in accounts">
<tr>
<td ><a ng-click="getloandetails(account.idAccount)">{{account.accountName}}</a></td>
<td>$ {{account.currentBalance}}</td>
</tr>
</tbody>
and in Angular side just do this:
$scope.getloandetails = function(accountId) {
alert('Gettring details for the accountId: ' + accountId);
};

Categories

Resources