Issue with UI-scroll and promisse - javascript

I just want to scroll downside and after that come back to the beginning of the list.
Now I can't use my grid.
I know that there are thousands of examples of how to do ui-scroll,
but there are no any example with Angular 1.5 components
Please help.
index.html
//add ui-scroll-viewport
<md-content flex layout-padding class="viewport" id="viewport-serviceDatasource" ui-scroll-viewport>
// added ui-scroll, this part is responsible for loading by week
<div layout="raw" layout-xs="column" class="week" layout-sm="column" layout-align="space-between start" flex="none"
ui-scroll="week in $ctrl.grid">
<!-- outlines days -->
<div flex="none" layout="column" layout-fill ng-repeat="day in week">
<!-- current day header-->
<div layout="row" layout-align="space-between center" flex-gt-sm="none" flex="none" style="height: 30px">
<div flex="none" class="md-body-1" style="min-width: 24px">{{::day.title}}</div>
</div>
</div>
</div>
</md-content>
app.js
class CalendarCtrl {
constructor($log, $q, $timeout, $scope) {
'ngInject';
this._$log = $log;
this._$q = $q;
this._$timeout = $timeout;
this._$scope = $scope;
this.grid = {};
// Tried to use $Scope
this._$scope.grid = {};
}
$onInit() {
// Get the first day of the week curry
let currDay = moment().weekday(0),
startDay = moment(currDay).add(-5,'w'),
endDay = moment(currDay).add(5,'w');
// Error here. I think so
this.getCalendarGrid(startDay, endDay).then(
(success) => {
// Get all our days, in the form of a grid
var result = success;
var grid = {};
grid.get = (index, count, success) =>{
index = index <= 0 ? index + 1 : index -1;
success(result.slice(index, index + count));
};
this.grid = grid;
this._$log.debug('Calendar: getCalendarGrid', this.grid);
},
(error) => this._$log.debug('Calendar: onInit, getCalendar error', error),
(week) => this._$log.debug('Calendar: onInit, getCalendar notify', week)
);
}
/**
*
* #returns {Promisse}
*/
getCalendarGrid(startDay, endDay){
let start = startDay, end = endDay;
let result = this._$q.defer(),
grid = {},
index = 0,
diff = end.diff(start,'d'),
day = {
title: null,
activity: []
},
week = {};
while (diff != 0){
// go through all the days.
day.title = start.format('DD');
angular.extend(week, {[start.format('YYYYMMDD')]: day});
day = {
title: null,
activity: []
};
// put by week
if ((diff % 7 == 1) || diff == 0){
week = { [start.format('YYYYWW')]: week };
angular.extend(grid,week);
result.notify(week);
week = {};
}
start.add(1,'d');
diff = end.diff(start,'d');
}
result.resolve(grid);
return result.promise;
}
}
Console screen
Console screen with errors

Related

Kendo MultiSelect - select value send to controller method MVC

In the form I have a kendo MultiSelect that allows you to select several add-ons to your order. After selecting, I want to show the price of the add-on but somehow I do not.
The value of the selected add-on is displayed without any problem, the problem occurs when I want to display the price it needs to get with GET from the controller.
The method in the controller returns an int value.
Could someone direct me in the right direction?
function onChange(e) {
var multiselect = $("#accessoriesCombo").data("kendoMultiSelect");
var accessoriesLabel = $("#accessoriesLabel");
var startDate = $("#rentStartPicker").data("kendoDateTimePicker").value();
var endDate = $("#rentEndPicker").data("kendoDateTimePicker").value();
var diffDay;
if (calculate(startDate, endDate) < 1) {
diffDay = calculate(startDate, endDate) + 1;
} else {
diffDay = calculate(startDate, endDate);
}
var textValues = "";
var arrayValues = this.value();
var total = 0;
arrayValues.forEach(function (item) {
textValues += item;
total += getPrice(item, diffDay);
});
accessoriesLabel.text(textValues + " (" + total + ")");
}
function getPrice(id, numberOgDays) {
var returnPrice = 0;
// return int Accessories Price
$.get('/Cars/GetAccessoriesPrice/?id=' + id + '&numberOfDays=' + numberOgDays, function (price) {
returnPrice = price;
return returnPrice;
}, 'json');
}
function calculate(first, second) {
var diff = Math.round((second - first) / 1000 / 60 / 60 / 24);
return diff;
}
<div class="select-vehicle" style="padding-top:10px">
#(Html.Kendo().MultiSelect().Name("accessoriesCombo").DataValueField("AccessoriesID").DataTextField("AccessoriesName")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("Accessories_Read", "Cars");
});
})
.HtmlAttributes(new { #style = "width:100%" })
.Placeholder("Volitelné příslušenství")
.AutoClose(false)
.Events(events =>
{
events.Change("onChange");
})
)
<script type="text/x-kendo-tmpl" id="accessoriesTemplate">
<div style="padding: 5px; vertical-align:middle">
<p>
<input type="checkbox" style="vertical-align:text-bottom" id="chb_accessories_#:AccessoriesID#" value="#:AccessoriesID#" /><label for="chb_accessories_#:AccessoriesID#" style="padding-left:5px"> #:AccessoriesName#</label>
<span style="font-size:12px; padding-left:5px">cena od: #:kendo.toString(data.LowestPrice, "c0", "cs-CZ")# / den</span>
</p>
</div>
</script>
</div>

My ng-click is not firing

I'm new to Angular, so please bear with me.
I have an app I'm building where you can hit an "X" or a heart to dislike/like something. I'm using a swipe library called ng-swippy.
I'm trying to use ng-click="clickLike()"for the "Like" button and ng-click="clickDislike()"but neither are firing. I can't figure out what's going on.
Here's the URL:
http://430designs.com/xperience/black-label-app/deck.php
deck.php code
<ng-swippy collection='deck' item-click='myCustomFunction'
data='showinfo' collection-empty='swipeend' swipe-left='swipeLeft'
swipe-right='swipeRight' cards-number='4' label-ok='Cool'
label-negative='Bad'>
</ng-swippy>
The template is called from card-tpl.html:
<div class="ng-swippy noselect">
<div person="person" swipe-directive="swipe-directive" ng-repeat="person in peopleToShow" class="content-wrapper swipable-card">
<div class="card">
<div style="background: url({{person.thumbnail}}) no-repeat 50% 15%" class="photo-item"></div>
<div class="know-label">{{labelOk ? labelOk : "YES"}}</div>
<div class="dontknow-label">{{labelNegative ? labelNegative : "NO"}}</div>
</div>
<div class="progress-stats" ng-if="data">
<div class="card-shown">
<div class="card-shown-text">{{person.collection}}</div>
<div class="card-shown-number">{{person.subtitle}}</div>
</div>
<div class="card-number">{{collection.length - (collection.indexOf(person))}}/{{collection.length}}
</div>
</div>
<div class="container like-dislike" >
<div class="circle x" ng-click="clickDisike()"></div>
<div class="icon-like" ng-click="clickLike()"></div>
<div class="clearfix"></div>
</div>
</div><!-- end person-->
<div class="clearfix"></div>
Controller.js
angular.module('black-label', ['ngTouch', 'ngSwippy'])
.controller('MainController', function($scope, $timeout, $window) {
$scope.cardsCollection = [
{
thumbnail: 'images/deck/thor_01.jpg',
collection: 'thoroughbred',
}, {
thumbnail: 'images/deck/thor_02.jpg',
collection: 'thoroughbred',
},
];
// Do the shuffle
var shuffleArray = function(array) {
var m = array.length,
t, i;
// While there remain elements to shuffle
while (m) {
// Pick a remaining element
i = Math.floor(Math.random() * m--);
// And swap it with the current element.
t = array[m];
array[m] = array[i];
array[i] = t;
}
return array;
};
$scope.deck = shuffleArray($scope.cardsCollection);
$scope.myCustomFunction = function(person) {
$timeout(function() {
$scope.clickedTimes = $scope.clickedTimes + 1;
$scope.actions.unshift({ name: 'Click on item' });
$scope.swipeRight(person);
});
};
$scope.clickLike = function(person) {
console.log($scope.count);
// swipeRight(person);
};
$scope.count = 0;
$scope.showinfo = false;
$scope.clickedTimes = 0;
$scope.actions = [];
$scope.picks = [];
var counterRight = 0;
var counterLeft = 0;
var swipes = {};
var picks = [];
var counts = [];
var $this = this;
$scope.swipeend = function() {
$scope.actions.unshift({ name: 'Collection Empty' });
$window.location.href = 'theme-default.html';
};
$scope.swipeLeft = function(person) {
//Essentially do nothing
$scope.actions.unshift({ name: 'Left swipe' });
$('.circle.x').addClass('dislike');
$('.circle.x').removeClass('dislike');
$(this).each(function() {
return counterLeft++;
});
};
$scope.swipeRight = function(person) {
$scope.actions.unshift({ name: 'Right swipe' });
// Count the number of right swipes
$(this).each(function() {
return counterRight++;
});
// Checking the circles
$('.circle').each(function() {
if (!$(this).hasClass('checked')) {
$(this).addClass('checked');
return false;
}
});
$('.icon-like').addClass('liked');
$('.icon-like').removeClass('liked');
$scope.picks.push(person.collection);
// console.log('Picks: ' + $scope.picks);
// console.log("Counter: " + counterRight);
if (counterRight === 4) {
// Calculate and store the frequency of each swipe
var frequency = $scope.picks.reduce(function(frequency, swipe) {
var sofar = frequency[swipe];
if (!sofar) {
frequency[swipe] = 1;
} else {
frequency[swipe] = frequency[swipe] + 1;
}
return frequency;
}, {});
var max = Math.max.apply(null, Object.values(frequency)); // most frequent
// find key for the most frequent value
var winner = Object.keys(frequency).find(element => frequency[element] == max);
$window.location.href = 'theme-' + winner + '.html';
} //end 4 swipes
}; //end swipeRight
});
Any thoughts and help is greatly appreciated!
The ng-click directive is inside an ng-repeat directive inside a directive with isolate scope. To find the clickLike() function it needs to go up two parents:
<!--
<div class="icon-like" ng-click="clickLike()"></div>
-->
<div class="icon-like" ng-click="$parent.$parent.clickLike()"></div>
For information, see AngularJS Wiki - Understanding Scopes.

Alternating add/subtract function Angularjs

I need to do a toggle button...when you click once, it will add money to a total price, if you click the button again and "deselect" it, it will subtract that amount from the total.
I have this HTML that is adding and removing a class to change the background color of the selected button -
<div class="col-md-4" ng-repeat="service in services_data track by $index">
<div ng-class="showDetails[$index] ? 'panel-warning': 'panel-default'" class="panel">
<button ng-click="$parent.showDetails[$index] = !$parent.showDetails[$index]; price(service.price, service.est_time_mins)" class="panel-heading btn"><span class="pull-left badge">$ {{service.price}}</span>{{service.name}}</button>
<div class="panel-body">
{{service.est_time_mins}} mins. {{service.style}}
</div>
</div>
</div>
and this controller -
app.controller('AppointmentController', ['$scope','services', function($scope, services) {
var data = {};
data.fn = 'services';
services.getData(data).success(function(return_data){
console.log(return_data);
$scope.services_data = return_data;
});
var data = {};
data.fn = 'get_barbers';
services.getData(data).success(function(rd){
$scope.barbers = rd;
console.log(rd);
});
$scope.total_price = 0;
$scope.time = 0;
$scope.price = function(price, time){
$scope.total_price = parseInt(price) + parseInt($scope.total_price);
$scope.time = parseInt(time) + parseInt($scope.time);
}
}]);
Probably pretty easy but I can't wrap my head around it. Thanks.
Use a boolean flag:
$scope.selected = false;
$scope.add = function(price) {
//If item is currently selected, subtract price
if ($scope.selected) $scope.total_price -= price;
//If item is currently NOT selected, add price
else $scope.total_price += price;
$scope.selected = !$scope.selected;
};

Angular JS indefinite execution of a function called inside a ng-repeat

I am building an app using google's QPX express and I created a service to call the QPX web service.
I noticed that when I inspect certain functions, I see that they are executing indefinitely. The functions are $scope.pageArray, $scope.humanizeTime.Can someone help me identify why this is the case.
I have an understanding of why this is happening, but am not able to identify the root cause. Somehow/Somewhere in the code I am suggesting to Angular that the model has changed and therefore Angular is running a $scope.$digest, but I cant seem to identify where.
var resultController =planeSearchControllers.controller('resultController',['$scope','$http','commonSharedService','flight', function($scope,$http,commonSharedService,flight){
var isDebugEnabled = true;
$scope.showResults = false;
$scope.showPlaneSearch = true;
$scope.showPlaneError = false;
$scope.planeView = false;
$scope.historyView = false;
$scope.$watch(function() {return commonSharedService.getMode();},function(newValue,oldValue){
console.log('New Mode is' + newValue);
if(newValue == 'plane'){
$scope.planeView = true;
$scope.historyView = false;
$scope.historyObj = [];
}else if(newValue == 'history'){
getHistory(commonSharedService.getUserName());
$scope.planeView = false;
$scope.historyView = true;
}
});
$scope.$watch(function (){return commonSharedService.getValidateInputs();},function (newValue,oldValue){
if(isDebugEnabled){
console.log('Value is changed for getValidateInputs ' + 'New Value is -->'+ newValue);
}
$scope.validateInputs = newValue;
if($scope.validateInputs == true) {
makePlaneCall();
$scope.showResults = true;
commonSharedService.setValidateInputs(undefined);
$scope.errorMsg = commonSharedService.getErrorMsg();
}
if($scope.validateInputs == false) {
$scope.showResults = false;
commonSharedService.setValidateInputs(undefined);
$scope.errorMsg = commonSharedService.getErrorMsg();
}
});
$scope.humanizeTime = function(time){
//var duration = new moment.duration(time, "minutes");
//var hours = duration.hours();
//var minutes = duration.minutes();
var hours = Math.floor(time/60);
var minutes = time - (60 * hours);
var str = hours == 0 ? '': hours + 'hours ' ;
str += minutes == 0 ? '': minutes + 'minutes';
return str;
};
//Page Filtering
$scope.currentPage = 1;
$scope.numPerPage = 5;
$scope.maxSize = 5;
$scope.numPerPage = 5;
$scope.numPages = function () {
if($scope.tripOption!=null )
return Math.ceil($scope.tripOption.length / $scope.numPerPage);
else
return 0;
};
$scope.pageArray = function () {
var input = [];
for(var i=0;i<$scope.numPages();i++){
input[i] = i+1;
}
return input;
};
var paging = function(arrayIn,pageNo,perPageNo){
var outArray = [];
if(arrayIn!=undefined){
var from = perPageNo * (pageNo-1);
var to = from + perPageNo;
if (to > arrayIn.length)
to= arrayIn.length;
//console.log(from);
//console.log(to);
//console.log(outArray);
for (var i =from; i<to ;i++)
outArray.push(arrayIn[i]);
}
return outArray;
};
$scope.paginationFilter = function (){
return paging($scope.tripOption,$scope.currentPage,$scope.numPerPage);
};
var makePlaneCall = function () {
$scope.appendObj = commonSharedService.getAppendObj();
$scope.jsonObj = commonSharedService.getJsonObj();
$scope.jsonObj['time'] = moment().format("ddd Do,YYYY HH:mm a");
var user = commonSharedService.getUserName();
if(user != undefined)
setHistory(user,$scope.jsonObj);
$scope.planeRequest = {};
$scope.requestObj = {};
var slice = [];
var slice1 ={};
var slice2 ={};
var slice3 ={};
{
slice1['origin'] = $scope.appendObj['departAirport'];
slice1['destination']= $scope.appendObj['multiCity'] ? $scope.appendObj['interimAirport'] :$scope.appendObj['arrivalAirport'];
slice1['date']= $scope.appendObj['departureDate'];
slice1['permittedDepartureTime'] ={
"earliestTime": $scope.appendObj['departureEarliest']
};
if($scope.appendObj['preferredCabin']!=undefined){
slice1['preferredCabin'] = $scope.appendObj['preferredCabin'];
}
slice.push(slice1);
}
if($scope.appendObj['multiCity'] == true){
slice2['origin'] = $scope.appendObj['interimAirport'];
slice2['destination']= $scope.appendObj['arrivalAirport'];
slice2['date']= $scope.appendObj['interimDate'];
slice2['permittedDepartureTime'] ={
"earliestTime": $scope.appendObj['interimEarliest']
};
if($scope.appendObj['preferredCabin']!=undefined){
slice2['preferredCabin'] = $scope.appendObj['preferredCabin'];
}
slice.push(slice2);
}
if($scope.appendObj['isReturnFlight'] == 'true'){
slice3['origin']=$scope.appendObj['arrivalAirport'];
slice3['destination'] = $scope.appendObj['departAirport'];
slice3['date']=$scope.appendObj['arrivalDate'];
slice3['permittedDepartureTime'] ={
"earliestTime": $scope.appendObj['arrivalEarliest']
};
if($scope.appendObj['preferredCabin']!=undefined){
slice3['preferredCabin'] = $scope.appendObj['preferredCabin'];
}
slice.push(slice3);
}
for(var property in $scope.jsonObj){
if($scope.jsonObj.hasOwnProperty(property)){
$scope.requestObj[property] = $scope.jsonObj[property];
}
}
$scope.requestObj['slice'] = slice;
//$scope.requestObj['passengers'] = $scope.jsonObj['passengers'];
$scope.requestObj['solutions'] = 5;
$scope.requestObj['refundable'] = false;
$scope.planeRequest['request'] =$scope.requestObj;
flight.search($scope.planeRequest,function(response){
$scope.result= response;
$scope.info = $scope.result.trips.data;
$scope.tripOption = $scope.result.trips.tripOption;
//console.log($scope.tripOption);
if($scope.tripOption!=null){
{
$scope.airport = $scope.info.airport;
$scope.city = $scope.info.city;
$scope.aircraft = $scope.info.aircraft;
$scope.tax = $scope.info.tax;
$scope.carrier = $scope.info.carrier;
$scope.showPlaneError = false;
$scope.paginationFilter();
}
}
else{
$scope.showPlaneError = true;
$scope.planeSearchErrorMsg = "No Solutions found. Please check your airport codes and set more liberal parameter for the search to see if something turns up.";
}
console.log(response);
},function(response){
console.log("error");
$scope.result= response;
console.log(response);
});
};
function setHistory(userName,historyObj){
var firstTime=true;
var ref = new Firebase("http://flight-searchdb.firebaseIO.com/History");
var historyRef = ref.child(userName);
historyRef.on("value", function(historySnapshotObj) {
if(firstTime==true){
var historySnapshot = historySnapshotObj.val();
console.log(historySnapshot);
var count;
if(historySnapshot!=null)
count = historySnapshot['count'];
console.log(count);
var obj ={};
if(count == undefined) {
obj['count'] = 0;
obj[0]= historyObj;
}else if(count < 9){
obj['count'] = ++count;
obj[count]= historyObj;
}else if(count == 9){
console.log(3);
obj['count'] = count;
for(var i=0;i<9;i++)
obj[i+1] = historySnapshot[i];
obj[0] = historyObj;
}
firstTime = false;
historyRef.update(obj);
}
else {
console.log("Wrong Place");
}
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
}
function getHistory(userName){
var ref = new Firebase("http://flight-searchdb.firebaseIO.com/History");
var usersRef = ref.child(userName);
usersRef.on("value", function(snapshot) {
for (var i=0;i<10;i++){}
var userHistory = snapshot.val();
var count;
var array=[];
if(userHistory!=null)
count = userHistory['count'];
if (count!=undefined) {
for (var i=0;i <count ; i++)
array.push(userHistory[i]);
}
$scope.historyObj = array;
$scope.$digest();
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
}
}]);
I tested all functions and all of them seem to be working , except that when I added the pagination I dont see any result.
P.S : I was using a filter before , but for the sake of debug , I moved the pagination logic into the controller. I also understand that I could have used a directive.(since I am displaying the result at only place, I decided to skip it.)
I am also adding the view below , in which I am using the controller.
<!-- Result Body-->
<div class="col-sm-6 col-md-6 col-lg-7" data-ng-controller="resultController">
<div class="container-fluid">
<div data-ng-show="planeView">
<div data-ng-hide="showResults">
<div><span></span><span>{{errorMsg}}</span></div>
</div>
<div data-ng-show="showResults">
<div class="showPlaneSearch" data-ng-show="showPlaneSearch">
<div class="query thumbnail">
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-6">
<span >Page</span>
<select data-ng-model="currentPage" id="selectPage" class="form-control col-xs-5 col-sm-5 col-md-5 col-lg-5"
data-ng-options="value for value in pageArray()" data-toggle="popover" data-trigger="hover" data-placement="right"
data-content="Select Page Number">
</select>
</div>
</div>
</div>
<ul class="planesResult">
{{currentPage}}
{{numPerPage}}
<li ng-repeat="trip in paginationFilter" class="thumbnail">
<div class="row phoneContents">
<!-- Image -->
<div class="hidden-xs hidden-sm hidden-md col-lg-2">
<img src="images/Airplane-Icon.png" />
</div>
<!-- Trip Total $$$ -->
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-10" >
<span class="price">{{trip.saleTotal}}</span>
</div>
<!-- Everything except Image -->
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-10">
<!--Each Slice -->
<div ng-repeat="slice in trip.slice" class="slice row">
<!-- Each Segment Origin-->
<span class="col-xs-hidden col-sm-4 col-md-4 col-lg-4">
<span ng-repeat="segment in slice.segment">
<span > {{segment.leg[0].origin}}--></span>
<span ng-show="$last"> {{segment.leg[0].destination}} </span>
</span>
</span>
<!-- Each Segment Origin-->
<span class="col-xs-12 col-sm-3 col-md-3 col-lg-3">{{humanizeTime(slice.duration)}}</span>
<span ng-repeat="segment in slice.segment" class="col-xs-hidden col-sm-4 col-md-4 col-lg-4">
<span ng-show="$first"> Depart at {{}} </span>
</span>
<br>
</div>
</div>
</div>
</li>
</ul>
</div>
<div class="showPlaneError" data-ng-show="showPlaneError">
<span class="thumbnail">{{planeSearchErrorMsg}}</span>
</div>
</div>
</div>
<div data-ng-show="historyView">
<pre>{{historyObj | json}}</pre>
</div>
</div>
</div>
I can't run code, but i see something suspicious, worth changing:
two places:
$scope.paginationFilter = function (){
return paging($scope.tripOption,
and
if($scope.tripOption!=null){
{
$scope.airport = $scope.info.airport;
$scope.city = $scope.info.city;
$scope.aircraft = $scope.info.aircraft;
$scope.tax = $scope.info.tax;
$scope.carrier = $scope.info.carrier;
$scope.showPlaneError = false;
$scope.paginationFilter();
I see that when tripOption!= null you call paginationFilter function, which uses tripOption.

Directive's code fires before I got data

This is continuation of this question Get other columns from select ng-options
I have the problems with my directive. First problem is that with the very first initial load of the form I can see correctly department and category, but item shows 'Select Item' instead of the item. The second problem is when I navigate to another row in the list, the initial values are not shown (e.g. everything is showing 'Select Department', 'Select Category', 'Select Item' instead of the values. I confirmed that in that situation I didn't retrieve the row's data yet. So, I need to run directive's code only after I got my data.
How can I resolve my problems?
Here is the whole code for the directive:
(function () {
'use strict';
var app = angular.module('sysMgrApp');
app.directive('smDci', ['departmentService', 'categoryService', 'itemService', smDci]);
function smDci(departmentService, categoryService, itemService) {
var directive = {
restrict: 'E',
scope: {
selectedDepartmentId: '=?departmentid',
selectedCategoryId: '=?categoryid',
selectedItemId: '=itemid',
selectedDci: '=?dci'
},
controller: ['$scope', 'departmentService', 'categoryService', 'itemService',
function ($scope, departmentService, categoryService, itemService) {
$scope.selectedDepartmentId = $scope.selectedDepartmentId || 0;
$scope.selectedCategoryId = $scope.selectedCategoryId || 0;
$scope.selectedItemId = $scope.selectedItemId || 0;
$scope.selectedDci = $scope.selectedDci || '';
var init = function () {
$scope.metaData = {};
window.console && console.log('Selected departmentId = ' + $scope.selectedDepartmentId +
' Selected categoryId = ' + $scope.selectedCategoryId + ' Selected ItemId = ' + $scope.selectedItemId);
departmentService.getAllDepartments().then(function (data) {
$scope.metaData.departments = data.departments;
//window.console && console.log('Got all departments...')
});
if ($scope.selectedDepartmentId == 0 && $scope.selectedCategoryId == 0 && $scope.selectedItemId != 0) {
itemService.getItemById($scope.selectedItemId).then(function (data) {
var item = data.item;
if (item != null) {
$scope.selectedItem = item;
$scope.selectedDepartmentId = item.departmeId;
$scope.selectedCategoryId = item.categoryId;
window.console && console.log('Initial selections are about to fire...')
getInitialSelections();
}
});
}
else {
getInitialSelections();
}
};
var getInitialSelections = function()
{
if ($scope.selectedDepartmentId != 0) {
$scope.departmentChanged($scope.selectedDepartmentId);
}
if ($scope.selectedCategoryId != 0) {
$scope.categoryChanged($scope.selectedCategoryId);
}
}
$scope.departmentChanged = function (departmentId) {
if (!departmentId) {
$scope.selectedCategoryId = '';
$scope.selectedItemId = '';
$scop.selectedItem = {};
$scope.selectedDci = '';
}
else
{
categoryService.getCategoriesByDepartmentId(departmentId).then(function (data) {
$scope.metaData.categories = data.categories;
//window.console && console.dir($scope.selectedItem);
});
}
};
$scope.categoryChanged = function (categoryId) {
if (!categoryId) {
$scope.selectedItemId = '';
$scope.selectedItem = null;
$scope.selectedDci = '';
}
else
{
itemService.getItemsByCategoryId(categoryId).then(function (data) {
$scope.metaData.items = data.items;
});
}
};
$scope.itemChanged = function(item)
{
$scope.selectedItemId = item.itemId;
$scope.selectedDci = item.department + item.category + item.item;
}
init();
}],
templateUrl: 'app/templates/smDci'
};
return directive;
}
})();
and its HTML:
<div class="row">
<label class="control-label col-md-2" title="#Labels.dci">#Labels.dci:</label>
<div class="col-md-3">
<select class="form-control" ng-model="selectedDepartmentId" name="department" id="department"
ng-options="d.departmeId as d.descrip for d in metaData.departments"
data-no:dirty-check
ng-change="departmentChanged(selectedDepartmentId)">
<option value="">#String.Format(Labels.selectX, Labels.department)</option>
</select>
</div>
<div class="col-md-3">
<select class="col-md-3 form-control" ng-model="selectedCategoryId" id="category" name="category"
ng-disabled="!selectedDepartmentId"
data-no:dirty-check
ng-change="categoryChanged(selectedCategoryId)"
ng-options="c.categoryId as c.descrip for c in metaData.categories | filter: {departmeId:selectedDepartmentId}">
<option value="">#String.Format(Labels.selectX, Labels.category)</option>
</select>
</div>
<div class="col-md-3">
<select class="col-md-3 form-control" ng-model="selectedItem" id="item" name="item"
ng-disabled="!selectedCategoryId"
ng-change="itemChanged(selectedItem)"
ng-options="c as c.descrip for c in metaData.items | filter: {departmeId:selectedDepartmentId, categoryId:selectedCategoryId}">
<option value="">#String.Format(Labels.selectX, Labels.item)</option>
</select>
<div class="field-validation-error">
<span ng-show="item.$error.required">#String.Format(Messages.isRequired, Labels.item)</span>
</div>
</div>
</div>
<div class="clearfix"></div>
And this is how I use it in the form:
<data-sm:dci itemid="currentCardAct.itemId" dci="currentCardAct.dci"></data-sm:dci>
Using the logging to console I can see that card data retrieved after I need, e.g. in the console I see
Selected departmentId = 0 Selected categoryId = 0 Selected ItemId = 0
CardActController.js:221 Current Card Activity data retrieved..
smDci.js:28 Selected departmentId = 0 Selected categoryId = 0 Selected ItemId = 0
CardActController.js:221 Current Card Activity data retrieved..
I guess I can add watches in the directive's code, but is it the only option?
I solved the problem by adding a watch. I'm now trying to solve the problem with the initial selection of the item and apparently it's a known problem as referenced here http://odetocode.com/blogs/scott/archive/2013/06/19/using-ngoptions-in-angularjs.aspx about initial selection.

Categories

Resources