Prettyphoto stopped working after I changed the href url to an angular tag: {{something.uri}}
Javascript:
jQuery(".prettyphoto").prettyPhoto({
theme: 'pp_default',
overlay_gallery: false,
social_tools: false,
deeplinking: false,
theme: 'dark_rounded'
});
$("a[rel^='prettyPhoto']").prettyPhoto();
HTML:
<div ng-show="model.fileList" ng-repeat="fileList in model.fileList">
<a ng-href="{{fileList.uri}}" class="prettyphoto">
<img ng-src="{{fileList.uri}}" class="img-thumbnail" width="100" alt="" />
</a>
</div>
Angular scope from blobstorage:
fileList: [
{
parentContainerName: documents
uri: https://xxxxxx.blob.core.windows.net/documents/20140702.jpg
filename: 20140702.jpg
fileLengthKilobytes: 293
}
]
app.factory('storageService',
["$http", "$resource", "$q",
function ($http, $resource, $q) {
//resource to get summaryRoles
var resourceStorageManager = $resource('/api/storageManager/:id', { id: '#id' });
return {
getFileList: function () {
var deferred = $q.defer();
resourceStorageManager.query(, function (data) {
deferred.resolve(data);
}, function (status) {
deferred.reject(status);
}
);
return deferred.promise;
}
};
}]);
app.controller('startController', ['$scope', '$http', '$timeout', '$upload', 'storageService', 'settings',
function startController($scope, $http, $timeout, $upload, storageService, settings, profileRepository, notificationFactory, $q) {
$http.defaults.headers.common = { 'RequestVerificationToken': $scope.__RequestVerificationToken };
$scope.model = {};
$scope.model.fileList = null;
$scope.model.roundProgressData = {
label: 0,
percentage: 0.0
};
$scope.$on("pic_profileone_main", function (event, profileExtInfo1) {
$scope.changeprofilepicmodel1 = angular.copy(profileExtInfo1);
refreshServerFileList();
});
$scope.$on("pic_profiletwo_main", function (event, profileExtInfo2) {
$scope.changeprofilepicmodel2 = angular.copy(profileExtInfo2);
refreshServerFileList2();
});
$scope.onFileSelect = function ($files, callernumber, foldername, blobtype) {
if (callernumber == 1) {
$scope.blobModel = angular.copy($scope.changeprofilepicmodel1);
$scope.blobModel.folderName = foldername;
$scope.blobModel.blobTypeCode = blobtype;
} else if (callernumber == 2) {
$scope.blobModel = angular.copy($scope.changeprofilepicmodel2);
$scope.blobModel.folderName = foldername;
$scope.blobModel.blobTypeCode = blobtype;
}
$scope.selectedFiles = [];
$scope.model.progress = 0;
// Assuming there's more than one file being uploaded (we only have one)
// cancel all the uploads
if ($scope.upload && $scope.upload.length > 0) {
for (var i = 0; i < $scope.upload.length; i++) {
if ($scope.upload[i] != null) {
$scope.upload[i].abort();
}
}
}
$scope.upload = [];
$scope.uploadResult = [];
$scope.selectedFiles = $files;
// Ok, we only want one file to be uploaded
// let's take the first one and that's all
var $file = $files[0];
// Only first element, single file upload
(function (index) {
$scope.upload[index] = $upload.upload({
url: settings.constants.uploadURL,
headers: { 'myHeaderKey': 'myHeaderVal' },
method: 'POST',
data: $scope.blobModel,
file: $file,
fileFormDataName: 'myFile'
}).then(function (response) {
var look = response;
$scope.model.progress = 100;
// you could here set the model progress to 100 (when we reach this point we now that the file has been stored in azure storage)
$scope.uploadResult.push(response.data);
$scope.$emit('ClearUploadPics');
refreshServerFileList();
}, null, function (evt) {
// Another option is to stop here upadting the progress when it reaches 90%
// and update to 100% once the file has been already stored in azure storage
$scope.model.progress = parseInt(100.0 * evt.loaded / evt.total);
$scope.model.roundProgressData.label = $scope.model.progress + "%";
$scope.model.roundProgressData.percentage = ($scope.model.progress / 100);
});
})(0);
};
function refreshServerFileList() {
storageService.getFileList().then(function (data) {
$scope.model.fileList = data;
}
);
}
function initialize() {
refreshServerFileList();
}
initialize();
$scope.$on("ClearProgressBar", function (event) {
$scope.selectedFiles = null;
});
}]);
I hope this is okay and more readable.
Related
I have an existing project in AngularJS. There is an HTML page with client address. Its markup is:
<div class="text-left m-t-lg">
<h5>
Address
</h5>
<address>
<div ng-show="customerInfo.companyName != ''"><small>{{customerInfo.companyName}}</small><br /></div>
<div ng-show="customerInfo.customerName != ''"><small>{{customerInfo.customerName}}</small><br /></div>
<div ng-show="customerInfo.address != ''"><small>{{customerInfo.address}}</small><br /></div>
<div ng-show="customerInfo.email != ''"><small>{{customerInfo.email}}</small></div>
</address>
</div>
The directive:
app.directive('addressHeader', function () {
return {
scope: {
addressHeaderInfo: '=info'
},
templateUrl: 'address/addressHeader.html',
controller: 'addressHeaderController',
controllerAs: 'ahc'
};
});
My issue is In addressHeaderController.js I don't see addressHeaderInfo or info or customerInfo object. I need to update this object. Where is this object initialized from? I don't know much about AngularJS.
Controller:
app.controller('addressHeaderController', ['$http', 'APIService', '$scope', '$stateParams', '$sessionStorage', '$translate', '$state', '$rootScope', '$timeout', '$locale', 'tmhDynamicLocale',
function ($http, APIService, $scope, $stateParams, $sessionStorage, $translate, $state, $rootScope, $timeout, $locale, tmhDynamicLocale) {
var ctl = this;
$scope.followingAddress = false;
$scope.followData = {};
$scope.issueDisplay = '';
$scope.showResend = true;
$scope.showLoyaltyColumn = $sessionStorage.userObject.clientInfo.showLoyaltyColumnOnSurveyDetail;
ctl.isOpen = false;
ctl.dateOptions = { showWeeks: false };
$scope.businessUnits = null;
$scope.targetDealership = null;
$scope.realignComment = null;
$scope.$watch('addressHeaderInfo', function () {
debugger;
//Where is $scope.addressHeaderInfo coming from?
if (typeof ($scope.addressHeaderInfo) != 'undefined') {
//Some operations here. Not related to assigning anything to $scope.
}
});
function getDepartmentData() {
//No assignment here as well.
}
$scope.resendData = function () {
if ($sessionStorage.clientObject.requiresResendJustification) {
$('#resendJustificationModal').modal('show');
}
else {
var resendData = {};
resendData.recordId = $scope.addressHeaderInfo.addressID;
resendData.statusId = 24;
APIService.postData(resendData, 'Address/UpdateResendStatus')
.then(function (data) {
if (data.status == 200) {
$rootScope.$broadcast('resendRequest');
}
else {
toastr["error"]('Error');
}
});
}
}
$scope.nextAddress = function () {
$rootScope.$broadcast('addressNavigation', $scope.AddressList[$scope.recordNumber]);
$scope.recordNumber = $scope.recordNumber + 1;
}
$scope.previousAddress = function () {
$rootScope.$broadcast('addressNavigation', $scope.AddressList[$scope.recordNumber-2]);
$scope.recordNumber = $scope.recordNumber - 1;
}
$scope.followAddress = function () {
APIService.postData($scope.addressHeaderInfo, 'Address/follow')
.then(function (data) {
if (data.status == 200) {
toastr["success"]($translate.instant('AddressFollowedSaved'));
$scope.followData = data.data;
$scope.followingAddress = true;
}
else {
toastr["error"]($translate.instant('AddressFollowedErrored'));
}
})
}
$scope.unfollowAddress = function () {
APIService.deleteData('Address/follow/' + $scope.followData.AddressFavoriteId)
.then(function (data) {
if (data.status == 200) {
toastr["success"]($translate.instant('AddressUnfollowedSaved'));
$scope.followingAddress = false;
}
else if (data.status == 500) {
toastr["error"]($translate.instant('AddressUnfollowedErrored'));
}
});
}
$scope.AddressReminder = function () {
$('#setReminderPopup').modal('show');
}
$scope.saveReminder = function () {
$scope.followData.notificationDate = $scope.followData.displayDate;
APIService.postData($scope.followData, 'Address/follow/reminder')
.then(function (data) {
if (data.status == 200) {
toastr["success"]($translate.instant('AddressReminderSaved'));
$('#setReminderPopup').modal('hide');
}
else {
toastr["error"]($translate.instant('AddressReminderErrored'));
}
})
}
$scope.realignAddress = function () {
if ($scope.addressHeaderInfo) {
if (!$scope.businessUnits) {
getBusinessUnits();
}
var bu = $scope.addressHeaderInfo.businessUnit;
if (bu) {
bu.realignDisplayName = bu.name + ', ' + bu.shippingCity + ', ' + bu.suppliedBusinessUnitNumber;
}
$scope.realignComment = null;
$('#realignPopup').modal('show');
}
}
$scope.saveRealignRequest = function () {
var realignedAddress = $scope.addressHeaderInfo;
var realignData = {
AddressId: $scope.addressHeaderInfo.AddressID,
businessUnitId: $scope.targetDealership.businessUnitID,
notes: $scope.realignComment
};
APIService.postData(realignData, 'Address/requestRealignment')
.then(function (data) {
if (data.status == 200) {
toastr["success"]($translate.instant('AddressRealignRequestSaved'));
$('#realignPopup').modal('hide');
realignedAddress.realignmentStatus = 'Pending'; // cause Realign button to disappear and "Realignment is pending" message to show
} else {
toastr["error"]($translate.instant('AddressRealignRequestErrored'));
}
});
}
$scope.$on('advanceToNextIssue', function (event, data) {
if ($scope.AddressList && ($scope.recordNumber < $scope.AddressList.length)) {
$scope.nextAddress();
}
});
}]);
I see this error when I press F12 in chrome, but strangely things still work. There seems to be no problems.
The controller with the name 'AccountUpdateViewModel' is not registered.
Here is my js file. Any idea why? The version of angualr I am using is 1.6.0 from nuget(I develop on Visual Studio)
var accountUpdateModule = angular.module('accountUpdate', ['common', 'ngRoute'])
.config(function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
$routeProvider.when(Avts.rootPath + 'account/update/step1', { templateUrl: Avts.rootPath + 'Templates/AccountUpdate/Step1.html', controller: 'AccountUpdateStep1ViewModel' });
$routeProvider.when(Avts.rootPath + 'account/update/step2', { templateUrl: Avts.rootPath + 'Templates/AccountUpdate/Step2.html', controller: 'AccountUpdateStep2ViewModel' });
$routeProvider.when(Avts.rootPath + 'account/update/step3', { templateUrl: Avts.rootPath + 'Templates/AccountUpdate/Step3.html', controller: 'AccountUpdateStep3ViewModel' });
$routeProvider.when(Avts.rootPath + 'account/update/confirm', { templateUrl: Avts.rootPath + 'Templates/AccountUpdate/Confirm.html', controller: 'AccountUpdateConfirmViewModel' });
$routeProvider.when(Avts.rootPath + 'account/update/successfullyupdated', { templateUrl: Avts.rootPath + 'Templates/AccountUpdate/Successfull.html', controller: 'AccountUpdateSuccessfullyUpdatedViewModel' });
// 5:40 Sec. If it does not find any of these steps in this little spa silo, then redirect to step1
$routeProvider.otherwise({ redirectTo: Avts.rootPath + 'account/update/step1' });
});
accountUpdateModule.controller("AccountUpdateViewModel", function ($scope, $http, $location, $window, viewModelHelper) {
// Nested ViewModels or sub viewmodels. See Video 138 3:40 Sec
// Things that are set up here in this view model(AccountRegisterViewModel) is bound to the priticular view Register.cshtml.
// see 4:50 Sec
$scope.viewModelHelper = viewModelHelper;
$scope.accountModelStep1 = new Avts.AccountUpdateModelStep1();
$scope.accountModelStep2 = new Avts.AccountUpdateModelStep2();
$scope.accountModelStep3 = new Avts.AccountUpdateModelStep3();
$scope.fetchDataToUpdate = function () {
viewModelHelper.apiGet('api/account/update', null,
function (result) {
$scope.accountModelStep1.Email = result.data.Email;
$scope.accountModelStep1.UserName = result.data.UserName;
$scope.accountModelStep2.FirstName = result.data.FirstName;
$scope.accountModelStep2.LastName = result.data.LastName;
$scope.accountModelStep3.Address = result.data.Address;
$scope.accountModelStep3.City = result.data.City;
$scope.accountModelStep3.State = result.data.State;
$scope.accountModelStep3.PostalCode = result.data.PostalCode;
});
}
$scope.fetchDataToUpdate();
//$scope.previous = function () {
// // 6:00 Sec
// $window.history.back();
//}
});
accountUpdateModule.controller("AccountUpdateStep1ViewModel", function ($scope, $http, $location, viewModelHelper, validator) {
viewModelHelper.modelIsValid = true;
viewModelHelper.modelErrors = [];
// No setpup rules for step 1 edit. Just showing Email and userName
//var accountModelStep1Rules = [];
//var setupRules = function () {
// accountModelStep1Rules.push(new validator.PropertyRule("Email", {
// required: {
// message: "Email is required",
// email: { message: "Email is not an email." }
// }
// }));
// accountModelStep1Rules.push(new validator.PropertyRule("Password", {
// required: { message: "Password is required" },
// minLength: { message: "Password must be at least 6 characters", params: 6 }
// }));
//accountModelStep1Rules.push(new validator.PropertyRule("PasswordConfirm", {
// required: { message: "Password confirmation is required" },
// custom: {
// validator: Avts.mustEqual, // See 143, 2:30
// message: "Password do not match",
// params: function () { return $scope.accountModelStep1.Password; } // must be function so it can be obtained on-demand
// }
//}));
//}
//$scope.fetchData = function () {
// viewModelHelper.apiGet('api/account/edit', null,
// function (result) {
// $scope.accountModelStep1.Email = result.data.Email;
// $scope.accountModelStep1.UserName = result.data.UserName;
// });
//}
$scope.step2 = function () {
$location.path(Avts.rootPath + 'account/update/step2');
// Video 144
// Pressing should just do validation and proceed to step 2.
//validator.ValidateModel($scope.accountModelStep1, accountModelStep1Rules);
//viewModelHelper.modelIsValid = $scope.accountModelStep1.isValid;
//viewModelHelper.modelErrors = $scope.accountModelStep1.errors;
//if (viewModelHelper.modelIsValid) {
// viewModelHelper.apiPost('api/account/register/validate1', $scope.accountModelStep1,
// function (result) {
// // See the video 144 3:35 Sec
// $scope.accountModelStep1.Initialized = true;
// $location.path(Avts.rootPath + 'account/edit/step2');
// },
// function (failureResult) {
// $scope.accountModelStep1.errors = failureResult.data;
// viewModelHelper.modelErrors = $scope.accountModelStep1.errors;
// viewModelHelper.modelIsValid = false;
// }
// );
//}
//else
// viewModelHelper.modelErrors = $scope.accountModelStep1.errors;
}
//setupRules();
//$scope.fetchData();
});
accountUpdateModule.controller("AccountUpdateStep2ViewModel", function ($scope, $http, $location, viewModelHelper, validator) {
viewModelHelper.modelIsValid = true;
viewModelHelper.modelErrors = [];
var accountModelStep2Rules = [];
var setupRules = function () {
accountModelStep2Rules.push(new validator.PropertyRule("FirstName", {
required: { message: "First name is required" }
}));
accountModelStep2Rules.push(new validator.PropertyRule("LastName", {
required: { message: "Last name is required" }
}));
}
// Video 146
$scope.step3 = function () {
validator.ValidateModel($scope.accountModelStep2, accountModelStep2Rules);
viewModelHelper.modelIsValid = $scope.accountModelStep2.isValid;
viewModelHelper.modelErrors = $scope.accountModelStep2.errors;
if (viewModelHelper.modelIsValid) {
viewModelHelper.apiPost('api/account/update/validate2', $scope.accountModelStep2,
function (result) {
$scope.accountModelStep2.Initialized = true;
$location.path(Avts.rootPath + 'account/update/step3');
},
function (failureResult) {
$scope.accountModelStep2.errors = failureResult.data;
viewModelHelper.modelErrors = $scope.accountModelStep2.errors;
viewModelHelper.modelIsValid = false;
}
);
}
else
viewModelHelper.modelErrors = $scope.accountModelStep2.errors;
}
$scope.backToStep1 = function () {
$location.path(Avts.rootPath + 'account/update/step1');
}
setupRules();
});
accountUpdateModule.controller("AccountUpdateStep3ViewModel", function ($scope, $http, $location, viewModelHelper, validator) {
if (!$scope.accountModelStep2.Initialized) {
// got to this controller before going through step 2
$location.path(Avts.rootPath + 'account/update/step2');
}
var accountModelStep3Rules = [];
var setupRules = function () {
accountModelStep3Rules.push(new validator.PropertyRule("Address", {
required: { message: "Address is required" }
}));
accountModelStep3Rules.push(new validator.PropertyRule("City", {
required: { message: "City is required" }
}));
accountModelStep3Rules.push(new validator.PropertyRule("State", {
required: { message: "State is required" }
}));
accountModelStep3Rules.push(new validator.PropertyRule("PostalCode", {
required: { message: "Postal code is required" },
pattern: { message: "Postal code is in invalid format", params: /^[1-9][0-9]{5}$/ }
}));
//accountModelStep3Rules.push(new validator.PropertyRule("CreditCard", {
// required: { message: "Credit Card # is required" },
// pattern: { message: "Credit card is in invalid format (16 digits)", params: /^\d{16}$/ }
//}));
//accountModelStep3Rules.push(new validator.PropertyRule("ExpiryDate", {
// required: { message: "Expiration Date is required" },
// pattern: { message: "Expiration Date is in invalid format (MM/YY)", params: /^(0[1-9]|1[0-2])\/[0-9]{2}$/ }
//}));
}
$scope.confirm = function () {
validator.ValidateModel($scope.accountModelStep3, accountModelStep3Rules);
viewModelHelper.modelIsValid = $scope.accountModelStep3.isValid;
viewModelHelper.modelErrors = $scope.accountModelStep3.errors;
if (viewModelHelper.modelIsValid) {
viewModelHelper.apiPost('api/account/update/validate3', $scope.accountModelStep3,
function (result) {
$scope.accountModelStep3.Initialized = true;
$location.path(Avts.rootPath + 'account/update/confirm');
},
function (failureResult) {
$scope.accountModelStep3.errors = failureResult.data;
viewModelHelper.modelErrors = $scope.accountModelStep3.errors;
viewModelHelper.modelIsValid = false;
}
);
}
else
viewModelHelper.modelErrors = $scope.accountModelStep3.errors;
}
$scope.backToStep2 = function () {
$location.path(Avts.rootPath + 'account/update/step2');
}
setupRules();
});
accountUpdateModule.controller("AccountUpdateConfirmViewModel", function ($scope, $http, $location, $window, viewModelHelper) {
if (!$scope.accountModelStep3.Initialized) {
// got to this controller before going through step 3
$location.path(Avts.rootPath + 'account/update/step3');
}
$scope.updateAccount = function () {
// Video 147 2:00 Sec
var accountModel;
accountModel = $.extend(accountModel, $scope.accountModelStep1);
accountModel = $.extend(accountModel, $scope.accountModelStep2);
accountModel = $.extend(accountModel, $scope.accountModelStep3);
viewModelHelper.apiPost('api/account/update', accountModel,
function (result) {
//$location.path(Avts.rootPath);
$location.path(Avts.rootPath + 'account/update/successfullyupdated');
//account/update/successfullyupdateded
//account/update/successfullyupdated
//$window.location.href = Avts.rootPath;
},
function (failureResult) {
$scope.accountModelStep1.errors = failureResult.data;
viewModelHelper.modelErrors = $scope.accountModelStep1.errors;
viewModelHelper.modelIsValid = false;
}
);
}
$scope.backToStep3 = function () {
$location.path(Avts.rootPath + 'account/update/step3');
}
});
//AccountUpdateSuccessfullyUpdatedViewModel
accountUpdateModule.controller("AccountUpdateSuccessfullyUpdatedViewModel", function ($scope, $http, $location, $window, viewModelHelper) {
});
You had 'AccountUpdateViewModel controller. but you didn't registered it in your route.config. if you didn't config means you never use it anywhere.
please remove unwanted model. or register it in the rout config section.
i import the file, in index.html and my problem solved,
<script src=".../AccountUpdateStep1ViewModel.js"></script>
I want to re-organize my code so that I can share a dialog page with different controllers (ie. each controller opens the same dialog)
Should my dialog be a service or a directive... I'm not sure how to make it available to the controllers and have access to scopes
Something like this:
app.controller('PropertiesCtrl', function($scope,$rootScope,$http, DTOptionsBuilder, DTColumnBuilder, apiserv, $filter, $mdDialog, $mdMedia){
$scope.getProperties = function(){
$scope.data=[];
//var url = 'http://www.filltext.com/?rows=10&fname={firstName}&lname={lastName}&delay=3&callback=JSON_CALLBACK';
var data = "?db="+ $rootScope.globals.currentUser.agents[$rootScope.globals.currentDB].db_name;
var url = apiserv+"api.properties.test.php"+data;
$http.jsonp(url).success(function(data){
$scope.data=data;
});
};
var vm = this;
function stateChange(iColumn, bVisible) {
console.log('The column', iColumn, ' has changed its status to', bVisible);
}
// TO-DO: Rather load from a Factory promise, like here: https://github.com/l-lin/angular-datatables/issues/14
// Example here: http://embed.plnkr.co/B9ltNzIRCwswgHqKD5Pp/preview
var data = "?db="+ $rootScope.globals.currentUser.agents[$rootScope.globals.currentDB].db_name;
var url = apiserv+"api.properties.test.php"+data;
vm.dtOptions = DTOptionsBuilder.fromSource(url)
.withBootstrap()
// Active Buttons extension
.withButtons([
//'columnsToggle',
'colvis',
'copy',
'print',
'excel'
])
.withOption('fnRowCallback',myCallback)
.withOption('order', [[ 3, "desc" ]])
.withOption('stateSave',true);
vm.dtColumns = [
DTColumnBuilder.newColumn('File_Num').withTitle('File'),
DTColumnBuilder.newColumn('Description').withTitle('Description'),
DTColumnBuilder.newColumn('street').withTitle('Street'),
DTColumnBuilder.newColumn('bedrooms').withTitle('Bed'),
DTColumnBuilder.newColumn('bathrooms').withTitle('Bath'),
DTColumnBuilder.newColumn('garages').withTitle('Garages'),
DTColumnBuilder.newColumn('car_port').withTitle('Car Ports').notVisible(),
DTColumnBuilder.newColumn('Current_Monthly_Rental').withTitle('Rental').renderWith(function(data, type, full) {
return $filter('currency')(data, 'R ', 2); //could use currency/date or any angular filter
})
];
})
.controller('PagesListCtrl', function($scope,$rootScope,$http, DTOptionsBuilder, DTColumnBuilder, apiserv, $filter, $mdDialog, $mdMedia){
$scope.page = {
title: 'Dashboard',
subtitle: 'Place subtitle here...'
};
});
function myCallback(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
$('td', nRow).bind('click', function() {
//$scope.$apply(function() {
showTabDialog(aData);
//});
});
return nRow;
};
function showTabDialog(ev) {
console.log(ev.file_id);
var data = "?db="+ $rootScope.globals.currentUser.agents[$rootScope.globals.currentDB].db_name+"&file="+ev.file_id;
var url = apiserv+"api.properties.view.php"+data;
console.log(url);
$http({url:url}).then(function(rs){
console.log(rs.data[0]);
$scope.propdata=rs.data[0];
$mdDialog.show({
controller: DialogController,
templateUrl: 'pages/properties/tabDialog.tmpl.html',
//parent: angular.element(document.body),
targetEvent: ev,
//onComplete: afterShowAnimation,
//scope:$scope,
//preserveScope: true
locals: { propdata: $scope.propdata }
})
.then(function(propdata) {
console.log(propdata);
//$scope.$parent.propdata = propdata; // Still old data
//vm.sname = propdata.street;
});
}, function(rs){
console.log("error : "+rs.data+" status : "+rs.status);
});
};
function DialogController($scope, $mdDialog, propdata) {
$scope.propdata = propdata;
$scope.form_size = "form-group-sm";
$scope.font_size = "font-size-sm";
$scope.hide = function(ret) {
//$scope.$apply(); Throws an error
$mdDialog.hide(ret);
}
$scope.changesize = function() {
var fsize = $scope.form_size.split("-").pop(); // "form-group-xs";
switch(fsize) {
case "sm" : fsize = "md";
break;
case "md" : fsize = "lg";
break;
case "lg" : fsize = "sm";
break;
}
$scope.form_size = "form-group-" + fsize;
$scope.font_size = "font-size-" + fsize;
}
}
This is how I had it and it worked, but as you can see the dialog is nested inside the controller and only usefull to that controller:
app
.controller('PropertiesCtrl', function($scope,$rootScope,$http, DTOptionsBuilder, DTColumnBuilder, apiserv, $filter, $mdDialog, $mdMedia){
$scope.page = {
title: 'Dashboard',
subtitle: 'Place subtitle here...'
};
$scope.getProperties = function(){
$scope.data=[];
//var url = 'http://www.filltext.com/?rows=10&fname={firstName}&lname={lastName}&delay=3&callback=JSON_CALLBACK';
var data = "?db="+ $rootScope.globals.currentUser.agents[$rootScope.globals.currentDB].db_name;
var url = apiserv+"api.properties.test.php"+data;
$http.jsonp(url).success(function(data){
$scope.data=data;
});
};
var vm = this;
function stateChange(iColumn, bVisible) {
console.log('The column', iColumn, ' has changed its status to', bVisible);
}
// TO-DO: Rather load from a Factory promise, like here: https://github.com/l-lin/angular-datatables/issues/14
// Example here: http://embed.plnkr.co/B9ltNzIRCwswgHqKD5Pp/preview
var data = "?db="+ $rootScope.globals.currentUser.agents[$rootScope.globals.currentDB].db_name;
var url = apiserv+"api.properties.test.php"+data;
vm.dtOptions = DTOptionsBuilder.fromSource(url)
.withBootstrap()
// Active Buttons extension
.withButtons([
//'columnsToggle',
'colvis',
'copy',
'print',
'excel'
])
.withOption('fnRowCallback',$scope.myCallback)
.withOption('order', [[ 3, "desc" ]])
.withOption('stateSave',true);
vm.dtColumns = [
DTColumnBuilder.newColumn('File_Num').withTitle('File'),
DTColumnBuilder.newColumn('Description').withTitle('Description'),
DTColumnBuilder.newColumn('street').withTitle('Street'),
DTColumnBuilder.newColumn('bedrooms').withTitle('Bed'),
DTColumnBuilder.newColumn('bathrooms').withTitle('Bath'),
DTColumnBuilder.newColumn('garages').withTitle('Garages'),
DTColumnBuilder.newColumn('car_port').withTitle('Car Ports').notVisible(),
DTColumnBuilder.newColumn('Current_Monthly_Rental').withTitle('Rental').renderWith(function(data, type, full) {
return $filter('currency')(data, 'R ', 2); //could use currency/date or any angular filter
})
/*DTColumnBuilder.newColumn('file_id').withTitle('').withClass('dt-right').renderWith(function(data, type, full) {
//return "<a href='#/app/statement/"+full.id+"' class='btn btn-default'>View</a>";
return "<a class=\"btn btn-default\" onclick='$(\"#myview\").click()'>View</a>";
}).notSortable()*/
];
$scope.showTabDialog = function(ev) {
console.log(ev.file_id);
var data = "?db="+ $rootScope.globals.currentUser.agents[$rootScope.globals.currentDB].db_name+"&file="+ev.file_id;
var url = apiserv+"api.properties.view.php"+data;
console.log(url);
$http({url:url}).then(function(rs){
console.log(rs.data[0]);
$scope.propdata=rs.data[0];
$mdDialog.show({
controller: DialogController,
templateUrl: 'pages/properties/tabDialog.tmpl.html',
//parent: angular.element(document.body),
targetEvent: ev,
//onComplete: afterShowAnimation,
//scope:$scope,
//preserveScope: true
locals: { propdata: $scope.propdata }
})
.then(function(propdata) {
console.log(propdata);
//$scope.$parent.propdata = propdata; // Still old data
//vm.sname = propdata.street;
});
}, function(rs){
console.log("error : "+rs.data+" status : "+rs.status);
});
};
function DialogController($scope, $mdDialog, propdata) {
$scope.propdata = propdata;
$scope.form_size = "form-group-sm";
$scope.font_size = "font-size-sm";
$scope.hide = function(ret) {
//$scope.$apply(); Throws an error
$mdDialog.hide(ret);
}
$scope.changesize = function() {
var fsize = $scope.form_size.split("-").pop(); // "form-group-xs";
switch(fsize) {
case "sm" : fsize = "md";
break;
case "md" : fsize = "lg";
break;
case "lg" : fsize = "sm";
break;
}
$scope.form_size = "form-group-" + fsize;
$scope.font_size = "font-size-" + fsize;
}
}
$scope.myCallback = function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
$('td', nRow).bind('click', function() {
$scope.$apply(function() {
$scope.showTabDialog(aData);
});
});
return nRow;
};
});
Here is factory to store and retrieve user from any controller:
app.factory('Auth', [, function () {
function getUser() {
return user;
}
var currentUser = getUser();
return {
currentUser: currentUser
}]);
And use it:
app.controller('controller', ['Auth', function(Auth) {
var currentUser = Auth.currentUser;
}]);
And don't forget to include new factory on page before controller.
I'm writing a management system for an ecommerce system. The app needs to create pricing rules on a per product/ per category basis.
SO ..... For a new price rule that has a CategoryID, I want to update all products with that CategoryId. How do I call all the Products from the pricing controller and then update them?
I want this function in the Pricing's controller to update Products with a CategoryId that was set in the form.
$scope.saveRule = function saveRule(row){
var CategoryId = row.CategoryId;
if(row.id =="newRecord"){
var roundup = $('#roundupnewRecord').val();
var percentage = $('#percentagenewRecord').val();
var pricing = new Pricing({
CategoryId: CategoryId,
roundup: roundup,
percentage: percentage
});
pricing.$save(function(response) {
$route.reload();
});
} else {
Pricing.get({
pricingId: row.id
}, function(pricing) {
pricing.roundup = $('#roundup'+row.id).val();
pricing.percentage = $('#percentage'+row.id).val();
pricing.$update(function() {
$route.reload();
});
});
}
}
Thanks in advance for any help.
Pricing Controller. - angular
'use strict';
angular.module('mean.pricing').controller('PricingController', [ '$route', '$http', '$scope', '$routeParams', '$location', 'Global', 'Pricing', function ($route, $http, $scope, $routeParams, $location, Global, Pricing) {
$scope.global = Global;
$scope.create = function() {
var pricing = new Pricing({
CategoryId: this.title,
content: this.content
});
pricing.$save(function(response) {
console.log(response);
$location.path('pricing/' + response.id);
});
this.title = '';
this.content = '';
};
function generateDefaultRule() {
return {
CategoryId: 0,
ProductId: '',
roundup: 2,
percentage: 1,
newRecord: 1,
id: 'newRecord'
}
}
$scope.addRule = function addRule(id) {
$scope.rowCollection.push(generateDefaultRule());
console.log();
};
$scope.saveRule = function saveRule(row){
var CategoryId = row.CategoryId;
if(row.id =="newRecord"){
var roundup = $('#roundupnewRecord').val();
var percentage = $('#percentagenewRecord').val();
var pricing = new Pricing({
CategoryId: CategoryId,
roundup: roundup,
percentage: percentage
});
pricing.$save(function(response) {
$route.reload();
});
} else {
Pricing.get({
pricingId: row.id
}, function(pricing) {
pricing.roundup = $('#roundup'+row.id).val();
pricing.percentage = $('#percentage'+row.id).val();
pricing.$update(function() {
$route.reload();
});
});
}
//Get Products with Relative CategoryId
}
$scope.update = function() {
var pricing = $scope.pricing;
if (!pricing.updated) {
pricing.updated = [];
}
pricing.updated.push(new Date().getTime());
pricing.$update(function() {
$location.path('pricing/' + pricing.id);
});
};
$scope.find = function() {
Pricing.query(function(pricing) {
$scope.pricing = pricing;
});
};
$scope.findOverall = function() {
$http.get('/Pricing/overall').then(function(pricing) {
$scope.overall = pricing;
});
};
$scope.findCategories = function() {
$http.get('/Pricing/categories').then(function(pricing) {
console.log(pricing);
$scope.categories = pricing.data;
});
};
$scope.findProducts = function() {
$http.get('/Pricing/products').then(function(pricing) {
$scope.products = pricing.data;
});
};
$scope.findOne = function() {
Pricing.get({
pricingId: $routeParams.pricingId
}, function(pricing) {
$scope.pricing = pricing;
});
};
$scope.remove = function(pricing) {
if (pricing) {
pricing.$remove();
for (var i in $scope.pricing) {
if ($scope.pricing[i] === pricing) {
$scope.pricing.splice(i, 1);
}
}
}
else {
$scope.pricing.$remove();
$location.path('pricing');
}
};
$scope.removeItem = function removeItem(row) {
Pricing.get({
pricingId: row.id
}, function(pricing) {
pricing.$remove(function() {
var index = $scope.rowCollection.indexOf(row);
if (index !== -1) {
$scope.rowCollection.splice(index, 1);
}
});
});
}
$scope.list = function(){
$('table').on('click', 'a' , function (event) {
var id = $(this).attr('id');
if($(this).hasClass('editButton')){
$('#percentage'+id).css('display','inline-block');
$('#roundup'+id).css('display','inline-block');
$('#percentageSpan'+id).css('display','none');
$('#roundupSpan'+id).css('display','none');
$('.actionButtonsDiv'+id).css('display','none');
$('#saveButtonDiv'+id).css('display','inline');
}
});
$http.get('/pricing').then(function(pricing) {
$scope.rowCollection = pricing.data;
});
$http.get('/category').then(function(categories) {
$scope.categories = categories.data;
});
}
}]);
Products Controller - angular
'use strict';
angular.module('mean.products').controller('ProductsController', ['$http', '$scope', '$routeParams', '$location', 'Global', 'Products', function ($http, $scope, $routeParams, $location, Global, Products) {
$scope.global = Global;
$scope.create = function() {
var product = new Products({
title: this.title,
content: this.content
});
product.$save(function(response) {
$location.path("products/" + response.id);
});
this.title = "";
this.content = "";
};
$scope.remove = function(product) {
if (product) {
product.$remove();
for (var i in $scope.products) {
if ($scope.products[i] === product) {
$scope.products.splice(i, 1);
}
}
}
else {
$scope.product.$remove();
$location.path('products');
}
};
$scope.update = function() {
var product = $scope.product;
if (!product.updated) {
product.updated = [];
}
product.updated.push(new Date().getTime());
product.$update(function() {
$location.path('products/' + product.id);
});
};
$scope.find = function() {
Products.query(function(products) {
// console.log(products);
$scope.products = products;
});
};
$scope.categories = function() {
var selected = {};
$('#multiple').on('click', function(){
$('.product-checkbox').each(function() {
if ($(this).is(":checked")) {
$(this).prop('checked', false);
}else{
$(this).prop('checked', true);
}
});
});
$.each( ['approveButton', 'rejectButton', 'multiButton'], function( index, value ){
$('.'+value).on('click', function(){
$('.product-checkbox').each(function() {
var productId = $(this).attr('id');
if ($(this).is(":checked")) {
if (value === 'rejectButton') {
var categoryId = 199;
}else{
var categoryId = $('#selectProduct'+$(this).attr('id')).val().replace('number:','');
}
Products.get({
productId: productId
}, function(product){
product.CategoryId = categoryId;
product.$update(function(result) {
});
});
}
//Approves checked and rejcts unchecked products
if (value == 'multiButton') {
if (!$(this).is(":checked")) {
Products.get({
productId: productId
}, function(product){
product.CategoryId = 199;
product.$update(function() {
});
});
}
}
});
$location.path('products/categories');
});
});
$http.get('/products/categories').then(function(products) {
$scope.products = products.data;
});
$http.get('/category').then(function(categories) {
$scope.categories = categories.data;
});
$http.get('/productCategoryMatchs').then(function(productCategoryMatchs) {
var pCMResponse = productCategoryMatchs.data;
var pcmArray = {};
for(var index in pCMResponse){
pcmArray[pCMResponse[index].ProductId] = pCMResponse[index].CategoryId;
}
$scope.pCMs = pcmArray;
});
};
$scope.findOne = function() {
Products.get({
productId: $routeParams.productId
}, function(product) {
$scope.product = product;
});
};
}]);
Products Controller -node
'use strict';
/**
* Module dependencies.
*/
var StandardError = require('standard-error');
var db = require('../../config/sequelize');
/**
* Find product by id
* Note: This is called every time that the parameter :productId is used in a URL.
* Its purpose is to preload the product on the req object then call the next function.
*/
exports.product = function(req, res, next, id) {
console.log('id => ' + id);
db.Product.find({ where: {id: id}}).then(function(product){
if(!product) {
return next(new Error('Failed to load product ' + id));
} else {
req.product = product;
return next();
}
}).catch(function(err){
return next(err);
});
};
/**
* Create a product
*/
exports.create = function(req, res) {
// augment the product by adding the UserId
req.body.UserId = req.user.id;
// save and return and instance of product on the res object.
db.Product.create(req.body).then(function(product){
if(!product){
return res.send('users/signup', {errors: new StandardError('Product could not be created')});
} else {
return res.jsonp(product);
}
}).catch(function(err){
return res.send('users/signup', {
errors: err,
status: 500
});
});
};
/**
* Update a product
*/
exports.update = function(req, res) {
// create a new variable to hold the product that was placed on the req object.
var product = req.product;
product.updateAttributes({
price: req.body.price,
CategoryId: req.body.CategoryId
}).then(function(a){
return res.jsonp(a);
}).catch(function(err){
return res.render('error', {
error: err,
status: 500
});
});
};
/**
* Delete an product
*/
exports.destroy = function(req, res) {
// create a new variable to hold the product that was placed on the req object.
var product = req.product;
product.destroy().then(function(){
return res.jsonp(product);
}).catch(function(err){
return res.render('error', {
error: err,
status: 500
});
});
};
/**
* Show an product
*/
exports.show = function(req, res) {
// Sending down the product that was just preloaded by the products.product function
// and saves product on the req object.
return res.jsonp(req.product);
};
/**
* List of Products
*/
exports.all = function(req, res) {
db.Product.findAll({}).then(function(products){
return res.jsonp(products);
}).catch(function(err){
return res.render('error', {
error: err,
status: 500
});
});
};
/**
* List of Products
*/
exports.list = function(req, res) {
db.Product.findAll({
limit : 20
}).then(function(products){
return res.jsonp(products);
}).catch(function(err){
return res.render('500', {
error: err,
status: 500
});
});
};
/**
* List of Products and there categories
*/
exports.categories = function(req, res) {
db.Product.findAll({
attributes : [
'name',
'id',
// 'ProductCategoryMatch.count'
],
where: {
CategoryId : null
},
// include : [
// { model: db.ProductCategoryMatch }
// ],
// order : [
// ]
limit: 20
}).then(function(products){
return res.jsonp(products);
}).catch(function(err){
return res.render(500, {
error: err,
status: 500
});
});
};
/**
* Article authorizations routing middleware
*/
exports.hasAuthorization = function(req, res, next) {
// if (req.product.User.id !== req.user.id) {
// return res.send(401, 'User is not authorized');
// }
next();
};
i'm writing an mobile application in javascript with angularJS and ionicframework (last beta v.11), i create dinamically an object and want to display all objects inside in a ng-repeat. Why nr-repeat don't display anything?
This is screen from my object:
I use this code for put values in scope:
$scope.distanceSuppliers = myCar;
And this is the code in html:
<ion-item ng-repeat="(id, supplier) in distanceSuppliers">
<div class="items item-button-right" ng-click="openDetails(id)">
{{supplier.name}}<br />
{{supplier.address}}<br />
</div>
</ion-item>
This is my complete code for JS:
.controller('suppliers', function($scope, cw_db, $ionicPopup, $ionicActionSheet, appdelegate, $rootScope, $firebase, $location, $ionicLoading, cw_position) {
$ionicLoading.show({
template: 'Updating data..'
});
var geocoder;
var tot = 0;
var done = 0;
geocoder = new google.maps.Geocoder();
cw_db.getData(cw_db.getSuppliers(), "", function(suppliers) {
cw_position.getPosition(function (error, position) {
suppliers.on('value', function(supp) {
$scope.distanceSuppliers = {};
tot = 0;
done = 0;
supp.forEach(function(childSnapshot) {
tot++;
var childData = childSnapshot.val();
if (childData.address) {
calculateDistance(childData, position.coords.latitude, position.coords.longitude);
}
});
});
$ionicLoading.hide();
});
});
function calculateDistance(childData, usrLat, usrLon) {
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [new google.maps.LatLng(usrLat, usrLon)],
destinations: [childData.address],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
done++;
var results = response.rows[0].elements;
childData.distance = results[0].distance.value;
$scope.distanceSuppliers.push(childData);
if (done == tot) {
console.log($scope.distanceSuppliers);
}
}
});
}
$scope.openDetails = function(index) {
//appdelegate.setCallId(index);
//$location.path("/app/supplierDetails");
}
})
what's wrong?
Not sure, but I believe you have a data binding update problem.
Try using the $timeout to force the render:
w_position.getPosition(function (error, position) {
$timeout(function() {
suppliers.on('value', function(supp) {
$scope.distanceSuppliers = {};
tot = 0;
done = 0;
supp.forEach(function(childSnapshot) {
tot++;
var childData = childSnapshot.val();
if (childData.address) {
calculateDistance(childData, position.coords.latitude, position.coords.longitude);
}
});
});
$ionicLoading.hide();
});
});
And don't forget to add the $timeout parameter to the controller:
.controller('suppliers', function($scope, ...<other parameters here>..., $timeout) {
I found the problem! Fix using $scope.$apply();
The problem was that i was writing in a different $scope using this code:
cw_position.getPosition(function (error, position) {
suppliers.on('value', function(supp) {
tot = 0;
done = 0;
supp.forEach(function(childSnapshot) {
tot++;
var childData = childSnapshot.val();
if (childData.address) {
calculateDistance(childData, position.coords.latitude, position.coords.longitude);
}
});
});
$ionicLoading.hide();
});
where cw_position.getPosition call a js with this code:
angular.module('cw_position', [])
.service('cw_position', function() {
this.getPosition = function(callback) {
navigator.geolocation.getCurrentPosition(
function (position) {
return callback(null, position);
},
function(error) {
return callback(error, null);
}
);
}
// Built google maps map option
//
this.getGoogleMapOptions = function (lat, lon, zoom, type) {
if (type == null) {
type = google.maps.MapTypeId.ROADMAP;
}
var mapOptions = {
center: new google.maps.LatLng(lat, lon),
zoom: zoom,
mapTypeId: type
};
return mapOptions;
}
});
navigator.geolocation.getCurrentPosition causes the 'problem'
Thx to all for your help