Firebase angularfire child.$asObject give properties undefined - angularjs

I've got this code:
factory
app.factory('Items', function($firebase,FIREBASE_URL) {
var ref = new Firebase(FIREBASE_URL);
var items = $firebase(ref.child('items')).$asArray();
var Item = {
all: function () {
return items;
},
create: function (item) {
return items.$add(item);
},
get: function (itemId) {
return $firebase(ref.child('items').child(itemId)).$asObject();
},
update: function (itemId, item) {
return $firebase(ref.child('items').child(itemId)).update(item);
},
delete: function (item) {
return items.$remove(item);
}
};
return Item;
});
route
app.config(function($stateProvider) {
$stateProvider
.state('items_update', {
url: '/items/update/:id',
templateUrl: 'views/items/form.html',
controller:'ItemsUpdateController',
resolve:{
item:function(Items,$stateParams){
return Items.get($stateParams.id);
}
}
})
});
controller
app.controller('ItemsUpdateController', function ($scope, item, $state) {
$scope.item = item;
console.log($scope.item.url);
$scope.add = function() {
Items.update($scope.item).then(function () {
$state.transitionTo('items');
});
}
});
why console.log($scope.item.url); give me undefined ?
but in the view I've got all the data
html
<form class="form-horizontal" role="form" name="form" data-ng-submit="add()">
<div class="form-group">
<input type="text" name="title" tabindex="1" class="form-control" placeholder="{{ 'items.form.title' | translate }}" data-ng-model="item.title" required="required" data-ng-minlength="3" data-ng-maxlength="25" user-feedback />
</div>
<div class="form-group">
<input type="text" name="ingredients" tabindex="2" class="form-control" placeholder="{{ 'items.form.ingredients' | translate }}" data-ng-model="item.ingredients" required="required" ng-pattern="/^\w(\s*,?\s*\w)*$/" user-feedback />
</div>
<div class="form-group">
<input type="text" name="price" tabindex="3" class="form-control" placeholder="{{ 'items.form.price' | translate }}" data-ng-model="item.price" required="required" data-smart-float user-feedback />
</div>
<div class="form-group">
<button type="button" tabindex="4" class="btn btn-default btn-lg" item="item" data-uploader>{{ 'items.form.upload' | translate }}</button>
<input type="text" name="url" style="display:none;" required="required" data-ng-model="item.url" />
</div>
<div class="form-group form-no-required clearfix">
<div class="pull-right">
<button type="submit" tabindex="5" class="btn btn-primary" data-ng-disabled="form.$invalid">{{ 'items.form.submit' | translate }}</button>
</div>
</div>
</form>
ENDS UP
as in the #Frank van Puffelen comment
I worked it out with:
app.controller('ItemsUpdateController', function($scope, item, $state) {
item.$loaded().then(function(data) {
$scope.item = data;
console.log($scope.item.url);
});
$scope.add = function() {
Items.update($scope.item).then(function() {
$state.transitionTo('items');
});
}
});

This is because by the time your console.log($scope.item.url); runs, the data hasn't been loaded from Firebase yet. Angular listens for a notification from Firebase/AngularFire to know when the data has loaded and then updates the view.
Also see angularfire - why can't I loop over array returned by $asArray? and Trying to get child records from Firebase.

Related

Angular Component two way binding not working

My component code:
(function () {
'use strict';
function SubscribeController(toaster, EmbHTTPFactory) {
var ctrl = this;
ctrl.submit = function () {
EmbHTTPFactory.subscribeToNewsletter(ctrl.email).then(function (res) {
toaster.pop('success', "User successfully subscribed");
},function (err) {
});
}
}
var app = angular.module('24hourdigitizing'),
config = {
templateUrl: "app/views/components/form-component.html",
controller: ['toaster', 'ng24hdDigitizing.factories.EmbHTTPFactory', SubscribeController],
bindings: {
label: '<',
button: '<',
action: '<',
classname: '<'
}
};
app.component('formComponent', config);
}());
Template HTML
<div class="container">
<div class="row">
<form action="" name="formElement" class="form-element">
<div class="form-group no-margin">
<label for="email" ng-if="$ctrl.label">{{ $ctrl.label }}</label>
<div class="">
<input class="form-control input-lg"
type="text"
id="email"
name="email"
ng-modal="$ctrl.email"
placeholder="Email..."
ng-required="true"
>
</div>
<button
type="button"
class="btn btn-primary btn-lg"
ng-disabled="formElement.$invalid"
ng-click="$ctrl.submit()"
>{{ $ctrl.button }}</button>
</div>
</form>
</div>
</div>
Issue:
As far as I know the $ctrl.email should be a two way binded variable. But whenever I submit the form I am getting undefined.
In the code ctrl.email is undefined.
Can anyone please explain if I am doing something wrong on this?
There is typo, it should be
ng-model="$ctrl.email"
instead of ng-modal

My AngularJS 1.5 component called booking-info isn't populating the input fields in my form with booking data

I have a form inside a bookingEdit component and a bookingInfo component containing the form's input fields. The fields inside bookingInfo component aren't being populated with the booking data. How can I get these fields to be populated using my booking-info and booking-edit components?
booking-edit.template.html
<form name="$ctrl.form" ng-submit="$ctrl.updateBooking()">
<fieldset>
<legend>Edit Booking</legend>
<booking-info booking="$ctrl.booking"></booking-info>
<button class="btn btn-success" type="submit">Save</button>
</fieldset>
</form>
booking-edit.component.js
'use strict';
angular.
module('bookingEdit').
component('bookingEdit', {
templateUrl: 'booking-edit.template.html',
controller: ['BookingService','$location',
function (BookingService,$location) {
let self = this;
self.$routerOnActivate = function(next, previous) {
self.booking = BookingService.get({ id: next.params.id });
};
self.updateBooking = function () {
BookingService.update({ id: self.booking.bookingId }, self.booking)
.$promise
.then(
function () {
$location.path('/list');
},
function (error) {
}
);
};
}
]
});
booking-info.component.js
angular.module('app').
component('bookingInfo', {
templateUrl: 'booking-details.html',
bindings: {
booking:'<'
},
controller: function(){
let self = this;
}
});
booking-details.html
<div class="form-group">
<label for="contactName">Contact Name</label>
<input required type="text" class="form-control" ng-model="booking.contactName">
</div>
<div class="form-group">
<label for="contactNumber">Contact Number</label>
<input required type="tel" class="form-control" ng-model="booking.contactNumber">
</div>
You seem to forgot the $ctrl in booking-details.html
<div class="form-group">
<label for="contactName">Contact Name</label>
<input required type="text" class="form-control" ng-model="$ctrl.booking.contactName">
</div>
<div class="form-group">
<label for="contactNumber">Contact Number</label>
<input required type="tel" class="form-control" ng-model="$ctrl.booking.contactNumber">
</div>

unable to get data from html in angular js

in this code of HTML, we get input text value and send to the Angular controller
so they get to work as defined in code.
<div class="row" ng-controller="RegionController">
<div class="col-lg-12" >
<div class="hpanel">
<div class="panel-heading">
<!-- <div panel-tools></div> -->
<h2>Region Master Entry</h2>
</div>
<div class="panel-body">
<!--change form name,and submit controller name-->
<form role="form">
<div class="form-group">
<label class="col-sm-2 control-label">Region Name</label>
<div class="col-sm-10">
<input type="text" placeholder="please enter Region name" class="form-control m-b" required name="Region Name" ng-model="formRegionData.region_name" >
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Region Code</label>
<div class="col-sm-10">
<input type="text" placeholder="please enter Region code" class="form-control m-b" required name="Region Code" ng-model="formRegionData.region_code">
</div>
</div>
<div class="form-group">
<div class="col-sm-3">
<label>Active</label>
</div>
<div class="checkbox checkbox-success col-sm-9">
<input id="checkbox3" type="checkbox" checked="" ng-model="formRegionData.status">
<label for="checkbox3">
</label>
</div>
</div>
<div class="form-group">
<div class="col-sm-4"></div>
<div class="col-sm-8">
<button class="btn btn-sm btn-primary btn-xl text-right" type="submit" ng-click="createRegion()"><strong> Save Region </strong></button>
</div>
</div>
{{formRegionData | json}}
</form>
</div>
</div>
</div>
</div>
"{{formRegionData | json}}" this will return in HTML input text result of but not send data to the controller
in Controller the code is written as
.controller('RegionController', function( $scope , regionService) {
$scope.createRegion = function() {
debugger;
vm.processing = true;
vm.message = '';
console.log(formRegionData);
regionService.SaveRegion( formRegionData )
.then(function(data) {
debugger;
//console.log(data);
//.success(function(data) {
vm.processing = false;
vm.storyData = {};
vm.message = data.message;
});
}
})
and my service to work according to Controller
.factory('regionService',function($http ){
var regionFactory = {};
regionFactory.SaveRegion = function(formRegionData) {
debugger;
return $http.post('/api/region/', formRegionData);
}
return regionFactory;
});
You have missed $scope
$scope.createRegion = function() {
debugger;
$scope.processing = true;
$scope.message = '';
console.log($scope.formRegionData);
regionService.SaveRegion($scope.formRegionData )
.then(function(data) {
debugger;
//console.log(data);
//.success(function(data) {
$scope.processing = false;
$scope.storyData = {};
$scope.message = data.message;
});
}
})
and remove ng-click="createRegion()" in your button control and add this code in your form tag by ng-submit. like,
<form ng-submit="createRegion()" role="form">
You have missed of $scope in form region data
Here is the link Jsfiddle
JS
angular.module('myApp', ['ngStorage'])
.controller('RegionController', function($scope, regionService) {
var vm = this;
$scope.createRegion = function() {
debugger;
vm.processing = true;
vm.message = '';
regionService.SaveRegion($scope.formRegionData)
.then(function(data) {
debugger;
//console.log(data);
//.success(function(data) {
vm.processing = false;
vm.storyData = {};
vm.message = data.message;
});
}
}).factory('regionService', function($http) {
var regionFactory = {};
regionFactory.SaveRegion = function(formRegionData) {
debugger;
return $http.post('/api/region/', formRegionData);
}
return regionFactory;
});

Fields values generated using ng-repeat is not getting while submit

Template for form submission. This page will display the form template. Initially it shows the TItle,Full Name. On clicking the 'Add Tags' link new input fields is been generated for entering tags.
On submit, the field input(story.tag) is not been included on RequestPayload
<form novalidate ng-submit="save()">
<div>
<label for="title">Title</label>
<input type="text" ng-model="story.title" id="title" required/>
</div>
<div>
<label for="firstName">Full Name</label>
<input type="text" ng-model="story.fullname" id="fullname" required/>
</div>
<div ng-controller="Note" >
<div ng-repeat="story in items ">
<label>Tag {{$index+1}}:</label>
<input type="text" ng-model="story.tag" id="tag" required/>
</div>
<a ng-click="add()">Add Tags</a>
</div>
<button id="save" class="btn btn-primary">Submit Story</button>
</form>
script :- app.js
angular.module("getbookmarks", ["ngResource"])
.factory('Story', function ($resource) {
var Story = $resource('/api/v1/stories/:storyId', {storyId: '#id'});
Story.prototype.isNew = function(){
return (typeof(this.id) === 'undefined');
}
return Story;
})
.controller("StoryCreateController", StoryCreateController);
function StoryCreateController($scope, Story) {
$scope.story = new Story();
$scope.save = function () {
$scope.story.$save(function (story, headers) {
toastr.success("Submitted New Story");
});
};
}
//add dynamic forms
var Note = function($scope){
$scope.items = [];
$scope.add = function () {
$scope.items.push({
inlineChecked: false,
tag: "",
questionPlaceholder: "foo",
text: ""
});
};
}
The story object inside ng-repeat is in another scope. This JSFiddle should do what you are looking for.
<div ng-app>
<div ng-controller="NoteCtrl">
<form novalidate ng-submit="save()">
<div>
<label for="title">Title</label>
<input type="text" ng-model="story.title" id="title" required/>
</div>
<div>
<label for="firstName">Full Name</label>
<input type="text" ng-model="story.fullname" id="fullname" required/>
</div>
<div ng-repeat="story in items">
<label>Tag {{$index+1}}:</label>
<input type="text" ng-model="story.tag" required/>
</div> <a ng-click="add()">Add Tags</a>
<button id="save" class="btn btn-primary">Submit Story</button>
</form>
<div ng-repeat="test in items">
<label>Tag {{$index+1}}: {{test.tag}}</label>
</div>
</div>
</div>
The NoteController:
function NoteCtrl($scope) {
$scope.story = {};
$scope.items = [];
$scope.story.tag = $scope.items;
$scope.add = function () {
$scope.items.push({
inlineChecked: false,
tag: "",
questionPlaceholder: "foo",
text: ""
});
console.log($scope.story);
};
}

angularfire using $loaded how to access data in a directive

This post is a follow up of
this
(the goal is set img to visibily and set the src)
html
<form class="form-horizontal" role="form" name="form" data-ng-submit="add()">
<div class="form-group">
<input type="text" name="title" tabindex="1" class="form-control" placeholder="{{ 'items.form.title' | translate }}" data-ng-model="item.title" required="required" data-ng-minlength="3" data-ng-maxlength="25" user-feedback />
</div>
<div class="form-group">
<input type="text" name="ingredients" tabindex="2" class="form-control" placeholder="{{ 'items.form.ingredients' | translate }}" data-ng-model="item.ingredients" required="required" ng-pattern="/^\w(\s*,?\s*\w)*$/" user-feedback />
</div>
<div class="form-group">
<input type="text" name="price" tabindex="3" class="form-control" placeholder="{{ 'items.form.price' | translate }}" data-ng-model="item.price" required="required" data-smart-float user-feedback />
</div>
<div class="form-group">
<button type="button" tabindex="4" class="btn btn-default btn-lg" item="item" data-uploader>{{ 'items.form.upload' | translate }}</button>
<input type="text" name="url" style="display:none;" required="required" data-ng-model="item.url" />
</div>
<div class="form-group form-no-required clearfix">
<div class="pull-right">
<button type="submit" tabindex="5" class="btn btn-primary" data-ng-disabled="form.$invalid">{{ 'items.form.submit' | translate }}</button>
</div>
</div>
</form>
js
app.controller('ItemsUpdateController', function ($scope, item, Items, $state) {
item.$loaded().then(function(data) {
$scope.item = data;
});
$scope.add = function() {console.log($scope.item);
/* Items.update(item.$id,$scope.item).then(function () {
$state.transitionTo('items');
});*/
}
});
app.directive('uploader', function() {
return {
restrict: 'A',
scope:{
item: '='
},
link: function(scope, element, attrs) {
if (window.File && window.FileReader && window.FileList && window.Blob) {
var fileElem = angular.element('<input type="file" style="display:none;">');
var imgElem = angular.element('<img src="" width="50" style="margin-left:10px;visibility:hidden;">');
element.after(fileElem);
element.after(imgElem);console.log(scope.item); //This give me undefined
/*if(scope.item.url){
imgElem.css('visibility','visible');
imgElem[0].src = scope.item.url;
}*/
fileElem.on('change',function(e){
e.stopPropagation();
var files = e.target.files;
var reader = new FileReader();
reader.onloadend = function () {
var url = reader.result;
imgElem.css('visibility','visible');
imgElem[0].src = url;
scope.$apply(function () {
scope.item.url = url;
});
}
reader.readAsDataURL(files[0]);
});
element.on('click', function(e) {
e.stopPropagation();
fileElem[0].click();
});
element.on('$destroy',function(){
element.off('click');
});
fileElem.on('$destroy',function(){
fileElem.off('change');
});
}
},
};
});
Why console.log(scope.item); give me undefined
but I can see the right values fill the form ?
and how can I get the value ?
(btw I've tried also with $timeout or $apply but both doesn't work)
I've also tried with
scope.$watch('item', function(newVal, oldVal){
console.log(newVal, oldVal);
}, true);
but I've got
[Exception... "Illegal operation on WrappedNative prototype object" nsresult: "0x8057000c (NS_ERROR_XPC_BAD_OP_ON_WN_PROTO)"
and I don't really understand why
console.log(scope.item);// Object { $$conf={...}, $id="-J_C-q-6bIW9PBZzqpAg"
console.log(angular.equals({}, scope.item));// but this is true !
Ugly ends up
//controller
$scope.item = item;
$scope.item.$loaded().then(function(data) {
$scope.item = data;
});
//directive
if(scope.item.$id){
scope.item.$loaded().then(function(data) {
imgElem.css('visibility','visible');
imgElem[0].src = data.url;
});
if anyone have got a better solution is welcome :)
}

Resources