Ionic Timezone Picker - angularjs

I'm trying to implement a Timezone picker in my Ionic project and I'm running into some issues. And to be a bit more specific, the timezone picker will be used on the edit profile page for a user. This timezone is important because my application allows the user to checkin (like Untappd) an item that they are currently trying. And I want the checkin date to match their timezone.
Where I'm stuck: I'm getting a bit confused due to the assortment of libraries offered. And I haven't had any luck implementing the solutions that I've found. I'm also a bit new to working with timezones to this degree, so another question is, should I allow the user to change their GMT offset? Or is it common to now just auto-detect this?
I've run across the following libraries, but as mentioned above I haven't had any luck implementing these in my Angular/Ionic project. (See below for code snippets.)
Libraries found:
timezone-js
angular-tz-extensions
tzdata-javascript.org
moment-timezone
My implementation:
index.html (I realize that this is overkill, but was trying to get any of them to work.)
<!-- moment/timezone -->
<script src="lib/timezone-js/src/date.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jstimezonedetect/1.0.4/jstz.js"></script>
<script src="lib/angular-tz-extensions/lib/angular-tz-extensions.min.js"></script>
<script src="lib/moment/min/moment.min.js"></script>
<script src="lib/angular-moment/angular-moment.min.js"></script>
<script src="lib/moment-timezone/moment-timezone.js"></script>
<script src="lib/moment-timezone/moment-timezone-utils.js"></script>
app.js
angular.module('curdcollective', [
'ionic',
'ionic.service.core',
'ionic.service.deploy',
'ionic.service.analytics',
'ionic.service.push',
'ngIOS9UIWebViewPatch',
[...](Removed for brevity),
'Timezones'
])
.constant(
'$timezones.definitions.location',
'/lib/angular-tz-extensions/tz/data'
)
I don't understand how $timezones is available, but that's what the docs say.
profile_edit.html (This is what I'm trying to get to.)
<label class="item item-input item-select">
<div class="input-label">Timezone</div>
<select name="data[User][timezone]" ng-model="item.User.timezone">
<option ng-repeat="zone in zones by zone.name" ng-value="zone.abbr">{{zone}}</option>
</select>
</label>
<label class="item item-input item-select">
<div class="input-label">GMT Offset</div>
<select name="data[User][gmt_offset]" ng-model="item.User.gmt_offset">
<option ng-repeat="offset in offsets" ng-value="offset">{{offset}}</option>
</select>
</label>
controllers.js
/**
* ProfileController
* Methods related to the user profile.
*/
.controller('ProfileController', function($state, $scope, $ionicHistory, $ionicPopup, $timezones, angularMomentConfig, $ionicModal, $stateParams, $resource, $sanitize, AuthService, LoadingService, ApiService, Me, $cordovaSocialSharing, BucketService) {
//Resolve a timezone
// var scope.timezone = $timezone.resolve('America/New_York', new Date());
// console.log(scope.timezone);
//Apply the timezone when a new one is selected
//from the edit profile view.
this.applyTimezone = function ($timezone) {
angularMomentConfig.preprocess = 'utc';
angularMomentConfig.timezone = $timezone.getName();
console.log(angularMomentConfig.timezone);
};
//#url https://github.com/chouseknecht/angular-tz-extensions
$timezones.getZoneList($scope);
$scope.$on('zonesReady', function(zones){
$scope.zones = zones;
console.log($scope.zones);
});
[...](Removed code for brevity.)
$scope.getTimeZonesList = function(moment){
console.log('getTimeZonesList');
var rZones = angular.forEach(moment.tz.zones(), function (zone) {
return {
name: zone.displayName,
abbr: moment.tz(zone.displayName).zoneAbbr()
};
});
console.log(rZones);
return rZones;
};
// Create the login modal that we will use later
$ionicModal.fromTemplateUrl('templates/profile_edit.html', {
scope: $scope
}).then(function(modal) {
$scope.editModal = modal;
});
//
$scope.showEditProfile = function(){
$scope.editModal.show();
};
$scope.hideEditProfile = function(){
$scope.editModal.hide();
};
})

I ended up making the following Angular Timezone service. It's not perfect and it could use some optimization and I could still use suggestions on how to make it better.
I'm auto-detecting if the user hasn't already set a timezone using Timezone.detect().
Here's the actual select code:
<select name="data[User][timezone]" ng-model="item.User.timezone" ng-options="zone.name for zone in zones" selected="item.User.timezone">
<option value="">Select Timezone</option>
</select>
See the gist at https://gist.github.com/robksawyer/98df7bb13d5efeac5dde.
/**
* Bower dependencies:
* timezone-js
* moment
* moment-timezone
* angular-moment
* angular-tz-extensions
*
* index.html:
* <script src="lib/timezone-js/src/date.js"></script>
* <script src="http://cdnjs.cloudflare.com/ajax/libs/jstimezonedetect/1.0.4/jstz.js"></script>
* <script src="lib/moment/min/moment-with-locales.min.js"></script>
* <script src="lib/moment-timezone/builds/moment-timezone-with-data.min.js"></script>
* <script src="lib/moment-timezone/moment-timezone-utils.js"></script>
* <script src="lib/angular-moment/angular-moment.min.js"></script>
* <script src="lib/angular-tz-extensions/lib/angular-tz-extensions.min.js"></script>
*/
angular.module('curdcollective.services', [
'angularMoment', 'Timezones'
])
/**
* TimezoneService
* Helper for Timezone related things
* #url https://github.com/chouseknecht/angular-tz-extensions
* #url https://github.com/urish/angular-moment
* #url http://momentjs.com/timezone/
*/
.service('TimezoneService', function(moment, $timezones, $filter, angularMomentConfig) {
//Get a list of timezones (via moment-timezone)
var timezones = [];
var autoDetectedTimezone = $timezones.getLocal() || 'UTC';
function pad(value) {
return value < 10 ? '0' + value : value;
}
function setDefaults(timezone){
if(!this.autoDetectedTimezone && !timezone){
return 'You need to detect the timezone first.';
}
//Set the default timezone
moment.tz.setDefault(this.autoDetectedTimezone);
angularMomentConfig.timezone = this.autoDetectedTimezone;
}
return {
//
//Initializes the timezone methods and loads required variables
//
initTimezones: function(){
this.timezones = [];
angular.forEach(moment.tz.names(), function (zone, key) {
this.push({
name: zone,
abbr: moment.tz(zone).zoneAbbr(),
offset: moment.tz(zone).format('Z')
});
}, this.timezones);
},
getTimezoneOffset: function(tz){
if(!tz){
tz = this.autoDetectedTimezone;
}
var rightNow = new Date();
var tzAlign = $timezones.align(rightNow, tz);
return tzAlign.getTimezoneOffset();
},
getHours: function(tz){
if(!tz){
tz = this.autoDetectedTimezone;
}
var rightNow = new Date();
var tzAlign = $timezones.align(rightNow, tz);
return tzAlign.getHours();
},
getGMTOffset: function(tz){
if(!tz){
tz = this.autoDetectedTimezone;
}
var rightNow = new Date();
var tzAlign = $timezones.align(rightNow, tz);
return $filter('date')(tzAlign,'Z');
},
//See https://github.com/chouseknecht/angular-tz-extensions
getLocale: function(tz){
if(!tz){
tz = this.autoDetectedTimezone;
}
return tz.locality;
},
//Handles setting the default timezone for the app.
setDefaults: function(timezone){
if(!this.autoDetectedTimezone && !timezone){
return 'You need to detect the timezone first.';
}
//Set the default timezone
moment.tz.setDefault(this.autoDetectedTimezone);
angularMomentConfig.timezone = this.autoDetectedTimezone;
},
//Handles auto-detecting the user's timezone
detect: function(){
this.autoDetectedTimezone = $timezones.getLocal() || 'UTC';
setDefaults(this.autoDetectedTimezone.name);
return this.autoDetectedTimezone.name;
},
//Retrieves a list of all timezones known
getTimezones: function(){
return this.timezones;
},
//DEPRECATED
/*createOffset: function(date) {
var sign = (date.getTimezoneOffset() > 0) ? '-' : '+';
var offset = Math.abs(date.getTimezoneOffset());
var hours = pad(Math.floor(offset / 60));
var minutes = pad(offset % 60);
return sign + hours + ':' + minutes;
}*/
};
});

Related

Selected value not displayed on AngularJS Select

My problem is when i change the value of the dropdown menu the value isn't displayed in the dropdown menu but the correct value is displayed in my console. Not sure why it isn't working at the moment because i have a same implementation of this in another project. Maybe i'm overlooking things.
On initialization i set
selected_type = types[0]
// What will result in Type1 being displayed on page load.
Fiddle you can find here: https://jsfiddle.net/596tzsh8/7/
Use:
ng-options="selected_type as selected_type.Name for selected_type in types track by selected_type.Id"
// ^
// the object itself
... instead of:
ng-options="selected_type.Id as selected_type.Name for selected_type in types track by selected_type.Id"
// ^
// the object's ID
Then, in your callback function, replace:
var typeID = this.selected_type;
// ^
// the object itself
... by:
var typeID = this.selected_type.Id;
// ^
// the object's ID
... and you're all set!
See your forked JSFiddle here, or play around with the snippet below.
var app = angular.module("app", ["controllers"])
var controllers = angular.module("controllers",[]);
controllers.controller('myController', function($scope){
$scope.types = [{
Id: 1,
Name: 'Type1'
}, {
Id: 2,
Name: 'Type2'
}, {
Id: 3,
Name: 'Type3'
}];
$scope.GetValueTypeDropdown = function () {
var typeID = this.selected_type.Id;
$scope.the_type = $.grep($scope.types, function (selected_type){
return selected_type.Id == typeID;
})[0].Name;
console.log($scope.the_type);
return $scope.the_type;
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="myController">
<form>
<select name="type" class="col-xs-12 dropdown-list"
ng-model="selected_type" class="col-xs-8"
ng-init="selected_type = types[0]"
ng-options="selected_type as selected_type.Name for selected_type in types track by selected_type.Id"
ng-change="GetValueTypeDropdown()">
</select>
</form>
</div>
</div>
You can change the select as follows,
<select name="type" class="col-xs-12 dropdown-list" ng-model="selected_type" class="col-xs-8" ng-init="selected_type = types[0]" ng-options="type as type.Name for type in types track by type.Id" ng-change="GetValueTypeDropdown()">
also you can have a $scope variable and display it on ng-change
$scope.GetValueTypeDropdown = function() {
console.log($scope.selected);
};
DEMO

Getting an 'Error: [$injector:unpr] Unknown provider: ' error

I'm trying to creata a dynamic drop down select menu. I'm getting an unknown provider error relating to a function I'm using to create a date range. Here is my code:
HTML
<ul data-role="listview" data-inset="true" >
<li>
<select id="makeSuperCategory" data-role="listview" ng-options="catagory as catagory.text for catagory in catagories.cast " ng-model="itemsuper" ng-change="changeData()">
</select>
</li>
</ul>
<ul data-role="listview" data-inset="true">
<li>
<select data-role="listview" ng-options="type as type.text for type in types.cast " ng-model="item1" ng-change="update()">
</select>
</li>
</ul>
Factories
var myApp = angular.module('myApp',[]);
myApp.factory('catagories',function(){
var makes = {};
makes.cast = [
{
value: "acura",
text: "Acura"
},
{
value: "audi",
text: "Audi"
},
{
value: "geo",
text: "Geo"
},
{
value: "hummer",
text: "Hummer"
},
];
return makes;
});
myApp.factory('acura',function( production_range,makesProductionEnded, makesInProduction){
var endedProductionObject = makesProductionEnded.filter(function( obj) {
return obj.make === this;
});
$scope.acura ={};
$scope.start = 1986 <!-- date Honda began production of the Acura product line -->
<!-- Set the most recent year option if still in production according to current month and model year change over October -->
$scope.setEnd = function(){
if($inArray(this, makesInProduction) > 0){
if(new Date().getMonth() < 10){
end = new Date().getFullYear();
} else {
end = new Date().getFullYear() + 1;
}
<!-- Set most recent year option if no longer in production according to year property value of object that matches this make in the endedProductionObject array -->
} else {
end = endedProductionObject.year;
}
return end;
}
$scope.acura.cast = [];
angular.foreach(years, function(value, year){
acura.cast.push(acura[year] = value);
});
return acura;
});
myApp.factory('audi',function(){
var audi = {};
audi.cast = [
<!--This will follow a similar pattern as acura once that is resolved -->
];
return audi;
});
myApp.factory('geo',function(){
var geo = {};
geo.cast = [
<!--This will follow a similar pattern as acura once that is resolved -->
];
return geo;
});
myApp.factory('hummer',function(){
var hummer = {};
hummer.cast = [
<!--This will follow a similar pattern as acura once that is resolved -->
];
return hummer;
});
Controller
myApp.controller('makeTypeCtrl',function($scope, acura, audi, geo,hummer, setNulls, catagories, production_range){
<!-- Push the model years into the years array according to the start and end dates -->
$scope.production_range = function(start, end){
var years = [];
for(var year = start; year <= end; year++){
years.push(year);
}
return years;
}
<!-- Defines the makes no longer in production and the date production ended for that make -->
$scope.makesProductionEnded = [{make:'eagle', year:1999}, {make:'geo', year:1997}]
<!-- Defines makes still in production -->
$scope.makesInProduction = ['acura', 'audi'];
$scope.catagories = catagories;
$scope.types = setNulls;
$scope.changeData = function() {
if($scope.itemsuper.text == "Acura") {
$scope.types = acura;
} else if($scope.itemsuper.text == "Audi") {
$scope.types = audi;
} else if($scope.itemsuper.text == "Geo") {
$scope.types = geo;
} else if($scope.itemsuper.text == "Hummer") {
$scope.types = hummer;
} else {
$scope.types = setNulls;
}
}
});
Here is a link to a jsFiddle
The issue is that you are trying to inject production_range into your acura factory. But production_range is a variable on a controller's scope, not a factory or service that can be injected.
The second parameter to a factory should be a function that takes dependencies as its parameters. By dependencies I mean factories / services or anything else thats created from a provider, see https://docs.angularjs.org/guide/services and https://docs.angularjs.org/guide/providers.
Read this as well: https://docs.angularjs.org/guide/di

Should $bind save child data added in an ng-repeat

Hi I have a problem with $bind, I am binding a model and outputting the models via a ng-repeat. The ng-repeat outputs the stored data and also offers some fields for adding/changing data. The changes are reflected in the scope but are not being synced to Firebase.
Is this a problem with my implementation of $bind?
The HTML:
<iframe id="fpframe" style="border: 0; width: 100%; height: 410px;" ng-if="isLoaded"></iframe>
<form>
<ul>
<li ng-repeat="asset in upload_folder" ng-class="{selected: asset.selected}">
<div class="asset-select"><input type="checkbox" name="selected" ng-model="asset.selected"></div>
<div class="asset-thumb"></div>
<div class="asset-details">
<h2>{{asset.filename}}</h2>
<p><span class="asset-filesize" ng-if="asset.size">Filesize: <strong><span ng-bind-html="asset.size | formatFilesize"></span></strong></span> <span class="asset-filetype" ng-if="asset.filetype">Filetype: <strong>{{asset.filetype}}</strong></span> <span class="asset-dimensions" ng-if="asset.width && asset.height">Dimensions: <strong>{{asset.width}}x{{asset.height}}px</strong></span> <span class="asset-type" ng-if="asset.type">Asset Type: <strong>{{asset.type}}</strong></span></p>
<label>Asset Description</label>
<textarea ng-model="asset.desc" cols="10" rows="4"></textarea>
<label>Creator</label>
<input type="text" ng-model="asset.creator" maxlength="4000">
<label>Release Date</label>
<input type="text" ng-model="asset.release">
<label for="CAT_Category">Tags</label>
<input type="text" ng-model="asset.tags" maxlength="255">
</div>
</li>
</ul>
</form>
The Controller: (fpKey is a constant that stores the Filepicker API key)
.controller('AddCtrl',
['$rootScope', '$scope', '$firebase', 'FBURL', 'fpKey', 'uploadFiles',
function($rootScope, $scope, $firebase, FBURL, fpKey, uploadFiles) {
// load filepicker.js if it isn't loaded yet, non blocking.
(function(a){if(window.filepicker){return}var b=a.createElement("script");b.type="text/javascript";b.async=!0;b.src=("https:"===a.location.protocol?"https:":"http:")+"//api.filepicker.io/v1/filepicker.js";var c=a.getElementsByTagName("script")[0];c.parentNode.insertBefore(b,c);var d={};d._queue=[];var e="pick,pickMultiple,pickAndStore,read,write,writeUrl,export,convert,store,storeUrl,remove,stat,setKey,constructWidget,makeDropPane".split(",");var f=function(a,b){return function(){b.push([a,arguments])}};for(var g=0;g<e.length;g++){d[e[g]]=f(e[g],d._queue)}window.filepicker=d})(document);
$scope.isLoaded = false;
// Bind upload folder data to user account on firebase
var refUploadFolder = new Firebase(FBURL.FBREF).child("/users/" + $rootScope.auth.user.uid + "/upload_folder");
$scope.upload_folder = $firebase(refUploadFolder);
$scope.upload_folder.$bind($scope,'upload_folder');
// default file picker options
$scope.defaults = {
mimetype: 'image/*',
multiple: true,
container: 'fpframe'
};
// make sure filepicker script is loaded before doing anything
// i.e. $scope.isLoaded can be used to display controls when true
(function chkFP() {
if ( window.filepicker ) {
filepicker.setKey(fpKey);
$scope.isLoaded = true;
$scope.err = null;
// additional picker only options
var pickerOptions = {
services:['COMPUTER', 'FACEBOOK', 'GMAIL']
};
var storeOptions = {
location: 'S3',
container: 'imagegrid'
};
var options = $.extend( true, $scope.defaults, pickerOptions );
// launch picker dialog
filepicker.pickAndStore(options, storeOptions,
function(InkBlobs){
uploadFiles.process(InkBlobs, $scope.upload_folder);
},
function(FPError){
$scope.err = FPError.toString();
}
);
} else {
setTimeout( chkFP, 500 );
}
})();
}])
I also have a service handling the input from Filepicker, this creates new entries in the firebase at the reference that is bound (using Firebase methods rather than AngularFire maybe this breaks the binding?)
.service('uploadFiles', ['$rootScope', 'FBURL', function($rootScope, FBURL) {
return {
process: function(InkBlobs, upload_folder) {
var self = this;
var countUpload = 0;
// write each blob to firebase
angular.forEach(InkBlobs, function(value, i){
var asset = {blob: value};
// add InkBlob to firebase one it is uploaded
upload_folder.$add(asset).then( function(ref){
self.getDetails(ref);
countUpload++;
});
});
// wait for all uploads to complete before initiating next step
(function waitForUploads() {
if ( countUpload === InkBlobs.length ) {
self.createThumbs(upload_folder, { multi: true, update: false, location: 'uploads' });
} else {
setTimeout( waitForUploads, 500 );
}
})();
},
getDetails: function(ref) {
// after InkBlob is safely stored we will get additional asset data from it
ref.once('value', function(snap){
filepicker.stat(snap.val().blob, {size: true, mimetype: true, filename: true, width: true, height: true},
function(asset) {
// get asset type and filetype from mimetype
var mimetype = asset.mimetype.split('/');
asset.type = mimetype[0].replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
asset.filetype = mimetype[1];
// add metadata to asset in upload folder
ref.update(asset);
});
});
},
createThumbs: function(ref, options) {
var self = this;
// default options
options.multi = options.multi || false;
options.update = options.update || false;
options.location = options.location || 'asset';
// if pathbase is not provided generate it based on provided location
if (!options.pathbase) {
if (options.location === 'assets') {
options.pathbase = FBURL.LIBRARY + "/assets/";
} else if (options.location === 'uploads') {
options.pathbase = "/users/" + $rootScope.auth.user.uid + "/upload_folder/";
} else {
throw new Error('SERVICE uploadFiles.createThumbs: options.location is not valid must be assets or uploads');
}
}
var generateThumb = function(blob, path) {
filepicker.convert( blob,
{ width: 200, height: 150, fit: 'crop' },
{ location: 'S3', access: 'public', container: 'imagegrid', path: '/thumbs/' },
function(tnInkBlob){
var refThumbBlob = new Firebase(FBURL.FBREF).child(path);
refThumbBlob.set(tnInkBlob);
},
function(FPError){
alert(FPError);
},
function(percentage){
// can use to create progress bar
}
);
};
if (options.multi) {
// look at all assets in provided ref, if thumbnail is mission or update options is true generate new thumb
angular.forEach(ref, function(value, key){
if (typeof value !== 'function' && (!value.tnblob || options.update)) {
// thumb doesn't exist, generate it
var blob = value.blob;
var path = options.pathbase + key + '/tnblob';
generateThumb(blob, path);
}
});
} else {
// getting thumbnail for a single asset
var refAsset = new Firebase(FBURL.FBREF).child(options.pathbase + ref);
var blob = refAsset.val().blob;
var path = options.pathbase + ref + '/tnblob';
generateThumb(blob, path);
}
}
};
}]);
So to recap, data is being saved to /users/$rootScope.auth.user.uid/upload_folder and this is being rendered in the HTML. Changes in the HTML form are reflected in the scope but not in Firebase, despite the binding:
var refUploadFolder = new Firebase(FBURL.FBREF).child("/users/" + $rootScope.auth.user.uid + "/upload_folder");
$scope.upload_folder = $firebase(refUploadFolder);
$scope.upload_folder.$bind($scope,'upload_folder');
Any ideas as to why this is? Is my implementation incorrect or am I somehow breaking the binding? Is $bind even supposed to work with ng-repeat in this manner?
Thanks
Shooting myself for how simple this is, the error was in how I defined the binding. You can't set the binding on itself, you need two separate objects in the scope...
The firebase reference $scope.syncdata loads the initial data and all modifications made to $scope.upload_folder will be synced to firebase.
var refUploadFolder = new Firebase(FBURL.FBREF).child("/users/" + $rootScope.auth.user.uid + "/upload_folder");
$scope.syncdata = $firebase(refUploadFolder);
$scope.syncdata.$bind($scope,'upload_folder');

To convert currency from US to UK in AngularJS

I tried this code to display but I need AngularJS to automatically convert currency:
<div ng-controller="ctrl">
default currency symbol ($): {{0.00 | currency}}
custom currency symbol (£): {{0.00 | currency:"£"}}
</div>
<script src="index.js"></script>
<script src="uk-locale.js"></script>
As #Andrey said, you should build your own custom filter to handle the currency conversion.
Here's a simple demo of how I would build such a thing:
angular.module('myModule').filter('currency', function() {
var defaultCurrency = '$';
return function(input, currencySymbol) {
var out = "";
currencySymbol = currencySymbol || defaultCurrency;
switch(currencySymbol) {
case '£':
out = 0.609273137 * input; // google
break;
default:
out = input;
}
return out + ' ' + currencySymbol;
}
});
check the online demo
AngularJs currencyFilter just formats output. If you want actually convert currency, you need to make custom filter, for example.
Here is possible example:
angular.module('myFilter', []).filter('currencyConverter', [function() {
function convert(inputValue, currecyId) {
// Your conversion code goes here
}
return function(inputValue, currencyId) {
return convert(inputValue, currencyId);
}
});

Angular - update models using $resource after $update

I'm trying to figure out how to update my models with services, when I get a response from the server.
My JSON structure:
var dgs = [{id :1,
driver:'Sam',
type: 'bus',
segments:[ {id:1,origin:'the bakery',arrival:'the store'},
{id:2,origin:'the store' ,arrival:'somewhere'}]
},
{ ... },
{ ... }
];
index.html:
<body ng-controller="dgCtrl">
<div ng-repeat="dg in dgs" drivegroup></div>
</body>
dg.html:
<div> {{ dg.driver }} </div>
<div> {{ dg.type }} </div>
<div ng-repeat="seg in dg.segments" segments></div>
segments.html:
<div>
<input ng-model="seg.origin" ng-blur="updateSegment()"/></div>
<div>
<input ng-model="seg.arrival" ng-blur="updateSegment()"/></div>
My controller is the following:
function dgCtrl($scope,$http,DriveGroup,Segment) {
var segment = new Segment;
$scope.dgs = DriveGroup.query(); // load & display all drive groups
$scope.updateSegment = function() {
var seg = this.seg;
segment.seg = this.seg;
segment.id = this.seg.id;
segment.$update(function(data,x) {
// seg.origin = data.origin - This updates the origin.
seg = data; // This doesn't work. How can I do this?
});
}
My services:
angular.module('dgService',['ngResource']).
factory("DriveGroup",function($resource) {
return $resource(
'/path/dgs',
{},
{update:{method:'PUT'}}
);
});
angular.module('Segment',['ngResource']).
factory('Segment',function($resource) {
return $resource(
'/path/seg/:id',
{id:'#id'},
{update:{method:'PUT'}}
);
});
My problem is I'm not sure how to update on a per-segment basis using $resource. I want to make a change on a certain segment, so I make a put request. I get the response from the server and want to update my model (which isn't working).
I'm new to Angular, so if you see any other blatant mistakes/or structure issues suggestions are appreciated. Thanks.
EDIT:
The following achieves the results I want, but is this correct?
$scope.updateSegment = function() {
var seg = this.seg,
segment = new Segment(seg);
segment.$update(function(data,x) {
angular.extend(seg,data);
});
}

Resources