AngularJs Filter: Generating notArray errors - javascript

I'm having an issue with a filter in my angularJS project.
We have a simple draft feature that allows users to save the contents of a large form as a JSON string in our database. They then can go to a section of the site to display and continue working on these forms. I want to provide them a filter on that page to filter by the date they saved the draft on.
Here is my markup:
<div ng-controller="savedFormCtrl" ng-cloak id="saved-form-wrapper"
class="border border-dark border-top-0 border-right-1 border-bottom-1
border-left-1 px-0" ng-init="getSavedForms()"
>
<!-- Search filters -->
<form name="savedFormsFilterWrapper" layout="row" flex="35" layout-align="end center" class="toolbar-search">
<!-- Date filter -->
<md-input-container flex="80">
<div class="text-light font-weight-bold float-left">Filter by saved date:</div>
<md-tooltip style="font-size:1em;">Filter your saved HRTF's</md-tooltip>
<md-datepicker name="dateFilter" class="hrtf-date savedFilterDatepicker"
md-date-locale="myLocale" data-ng-model="savedFormFilters" ng-blur="setFilterDate()"
md-placeholder="" md-open-on-focus
aria-label="Saved forms date filter">
</md-datepicker>
</md-input-container>
</form>
<!-- Saved forms body -->
<div id="savedFormAcc" class="accordion col-md-12 pt-3">
<!-- Accordion item Header -->
<div class="card" ng-repeat="item in savedForms | filter:savedFormFilters">
<div class="card-header savedFormItem" id="savedForm{{$index}}" data-toggle="collapse" data-target="#collapse{{$index}}">
<md-button class="md-raised md-primary" data-toggle="collapse"
data-target="#collapse{{$index}}" aria-expanded="false"
aria-controls="collapse{{index}}"
>
Form Saved on {{ item.savedOn }} - Click to expand
</md-button>
</div>
<!-- Accordion body continues on below -->
</div>
</div>
And my JS:
(function () {
'use strict';
angular.module('hrtf')
.controller('savedFormCtrl', ['$scope', '$window', 'formService',
function savedFormCtrl($scope, $window, formService) {
$scope.savedFormFilters = '';
//Get users's saved forms
$scope.savedForms = {};
$scope.getSavedForms = function(){
formService.getSavedForms()
.then(saved => {
saved.forEach( item =>{
item.data_json = JSON.parse(item.data_json);
});
$scope.savedForms = saved;
return $scope.savedForms;
};
}
]);
})();
Now, the filter works. But whenever The page is loaded, anywhere from 20-50 errors appear, all with the contents Error: [filter:notarray] Expected array but received: {}
All I need to do here is provide a simple filter on a string value to the parent objects savedOn: xxData Herexx value.
What am I doing wrong?

Turns out, I had a similar issue to this post
Basically, my ng-repeat and filter were initializing before the associated model could load. Initializing the model as a blank array and then creating the filter as part of the promise chain did the trick:
//Get users's saved forms
$scope.savedForms = [];
$scope.getSavedForms = function(){
formService.getSavedForms()
.then(saved => {
//Convert and format items here
$scope.savedForms = saved;
$scope.savedFormFilters = { savedOn: ''};
return $scope.savedForms;
}).catch(e => { console.error(e);
});
};
Pretty basic, but I'll leave it here in case it helps someone in the future :)

Related

AngularJS: Bind data returned from a modal to row it was clicked from

Using AngularJS here.
I am working on a UI which has a dropdown. Based on what the user selects I show 2 tabs to the user.
Each tab data is returned from a service which just returns an array of data (string).
Against each string value returned I show a button against it. When you click the button it opens a modal popup where the user can select some data.
When they close the modal I return the data back to the controller.
The normal flow of binding data to tab, opening modal and returning data from modal all works fine.
What I am not able to understand or design is how to bind the returned data against the button or row which it was clicked from
For example as below:
Tab1
String1 - Button1
String2 - Button2
String3 - Button3
If I open the modal by clicking button1, how do I find out button1 was pressed and bind back data that was returned from its modal.
Some of the relevant code as below:
<div id="params" ng-if="type.selected">
<tabset class="tabbable-line">
<tab heading="Sets" ng-if="sets" active="tab.set">
<div class="form-group m-grid-col-md-8 param" style="margin-top:5px"
ng-repeat="set in sets" >
<label class="control-label col-md-3 param-label">{{set}}
</label>
<button ng-click="openModal()" class="btn btn-info btn-sm">
Select
</button>
</div>
</tab>
<tab heading="Tables" ng-if="tables" active="tab.table">
<div class="form-group m-grid-col-md-8 param"
ng-repeat="table in tables">
<label class="control-label col-md-3 param-label">{{table}}
</label>
<button ng-click="openModal()" class="btn btn-info btn-sm">
Select
</button>
</div>
</tab>
</tabset>
</div>
Controller:
$scope.onChangeType = function (selectedValue) {
$scope.getData(selectedValue);
};
$scope.getData = function (selectedValue) {
//Commenting out the service part for now and hardcoding array
// service.getData(selectedValue).then(function (res) {
$scope.sets = ['Set1', 'Set2', 'Set3'];
$scope.tables = ['Table1', 'Table2'];
// });
};
$scope.openModal = function () {
myFactory.defineModal().then(function (response) {
//how to bind data from response
});
};
I have created a plnkr for this sample as:
http://plnkr.co/edit/vqtQsJP1dqGnRA6s?preview
--Edited--
<div class="form-group m-grid-col-md-8 param" ng-repeat="table in tables">
<label class="control-label col-md-3 param-label">{{table}}
</label>
<button ng-click="openModal(table)" class="btn btn-info btn-sm">
Select
</button>
<span>
{{table.utype}}
</span>
</div>
Pass the table object as an argument to the openModal function:
<button ng-click="openModal(table)">Select</button>
Use it in the openModal function:
$scope.openModal = function (table) {
myFactory.defineModal().then(function (result) {
table.utype = result.utype;
table.minvalue = result.minvalue;
});
};
Be sure to close the modal with the result:
$scope.ok = function () {
var result = {
utype: $scope.utype,
minvalue: $scope.minvalue,
};
$modalInstance.close(result);
};
Keep in mind that modals are considered disruptive and are despised by user.
Generally speaking, disruptions and distractions negatively affect human performance, a common finding in cognitive psychology. Many studies have shown that distraction greatly increases task time on a wide variety of tasks.
For more information, see
What research is there suggesting modal dialogs are disruptive?
While I dont get any error not but I dont get the text returned.
Be sure to furnish objects to the ng-repeat:
$scope.getData = function (selectedValue) {
//Commenting out the service part for now and hardcoding array
// service.getData(selectedValue).then(function (res) {
̶$̶s̶c̶o̶p̶e̶.̶t̶a̶b̶l̶e̶s̶ ̶=̶ ̶[̶'̶T̶a̶b̶l̶e̶1̶'̶,̶'̶T̶a̶b̶l̶e̶2̶'̶]̶;̶
$scope.tables = [
{name:'Table1',},
{name:'Table2',},
];
// });
};
The DEMO on PLNKR
Try to pass the table to openModal in your template
<button ng-click="openModal(table)"
Now you can use it as a reference in your openModal function
$scope.openModal = function (table) {
// table === the clicked table
}

Form modal binding in laravel with vue js

I have 2 models Tour.php
public function Itinerary()
{
return $this->hasMany('App\Itinerary', 'tour_id');
}
and Itinerary.php
public function tour()
{
return $this->belongsTo('App\Tour', 'tour_id');
}
tours table:
id|title|content
itineraries table:
id|tour_id|day|itinerary
In tour-edit.blade.php view I have used vue js to create or add and remove input field for day and plan dynamically.
Code in tour-create.blade.php
<div class="row input-margin" id="repeat">
<div class="col-md-12">
<div class="row" v-for="row in rows">
<div class="row">
<div class="col-md-2">
<label >Day:</label>
<input type="text" name="day[]"
class="form-control">
</div>
<div class="col-md-8">
{{ Form::label('itinerary', " Tour itinerary:", ['class' => 'form-label-margin'])}}
{{ Form::textarea('itinerary[]',null, ['class' => 'form-control','id' => 'itinerary']) }}
</div>
<div class="col-md-2">
<button class="btn btn-danger" #click.prevent="deleteOption(row)">
<i class="fa fa-trash"></i></button>
</div>
</div>
</div>
<div class="row">
<button class="btn btn-primary add" #click.prevent="addNewOption" >
<i class="fa fa-plus"></i> Add Field</button>
</div>
</div>
</div>
I want to populate these fields with their respective data. But all data i.e itinerary belonging to a tour are being displayed in itinerary textbox in JSON format.
My vue js sript is:
<script>
var App = new Vue({
el: '#repeat',
data: {
day:1 ,
rows:[
#foreach ($tour->itinerary as $element)
{day: '{{$element->day}}', plan: '{{$element->plan}}'},
#endforeach
]
},
methods: {
addNewOption: function() {
var self = this;
self.rows.push({"day": "","itinerary":""});
},
deleteOption: function(row) {
var self = this;
self.rows.splice(row,1);
},
}
});
</script>
I would avoid mixing blade into JavaScript, instead the best option is to make an ajax call to an api route which returns your data in json, which can then be processed by Vue:
methods:{
getItinerary(){
axios.get('api/itinerary').then(response => {
this.itinerary = response.data;
})
}
}
However, with this approach you will likely need to use vue-router rather than laravel web routes, which puts us into SPA territory.
If that's not an option (i.e. you still want to use blade templates), you should take a look at this answer I gave the other day which shows you how to init data from your blade templates.
What you seem to be doing is using laravel's form model binding to populate your forms, not Vue, so your model data is not bound to the view. So, you will need to decide which one you want to use. If it's vue you just want to use a normal form and bind the underlying data to it using v-model:
Now any updates in the view will automatically be updated by Vue. I've put together a JSFiddle that assumes you will want to continue using Laravel web routes and blade templates to show you one approach to this problem: https://jsfiddle.net/w6qhLtnh/

How to dynamically append templates to a page in Angular

So the situation is as follows:
I have an input bar where a user can search up a business name or add a person's name (and button to select either choice). Upon hitting enter I want to append a unique instance of a template (with the information entered by the user added). I have 2 templates I've created depending of if the user is searching for a business or a person.
One approach I've thought about is creating an object with the data and adding it with ng-repeat, however I can't seem to get the data loaded, and even then don't know how I can store reference to a template in my collection.
The other idea I've come across is adding a custom directive. But even then I've yet to see an example where someone keeps appending a new instance of a template with different data.
Here is the code so far:
payments.js:
angular.module('payment-App.payments',['ngAutocomplete'])
.controller('paymentController', function($scope, $templateRequest/*, $cookieStore*/) {
$scope.businessID;
$scope.address;
$scope.isBusiness = false;
$scope.payees = [];
$scope.newPayee = function () {
this.businessID = $scope.businessID;
this.address = $scope.address;
}
$scope.submit = function () {
var text = document.getElementById("businessID").value.split(",");
$scope.businessID = text[0];
$scope.address = text.slice(1).join("");
$scope.newPayee();
}
$scope.addPayee = function () {
$scope.submit();
$scope.payees.push(new $scope.newPayee());
console.log($scope.payees);
}
$scope.selectBusiness = function () {
//turns on autocomplete;
$scope.isBusiness = true;
}
$scope.selectPerson = function () {
//turns off autocomplete
$scope.isBusiness = false;
}
$scope.fillAddress = function () {
// body...
}
})
.directive("topbar", function(){
return {
restrict: "A",
templateUrl: 'templates/businessTemplate.html',
replace: true,
transclude: false,
scope: {
businessID: '=topbar'
}
}
})
payments.html
<h1>Payments</h1>
<section ng-controller="paymentController">
<div>
<div class="ui center aligned grid">
<div class="ui buttons">
<button class="ui button" ng-click="selectBusiness()">Business</button>
<button class="ui button arrow" ng-click="selectPerson()">Person</button>
</div>
<div class="ui input" ng-keypress="submit()">
<input id="businessID" type="text" ng-autocomplete ng-model="autocomplete">
</div>
<div class="submit">
<button class="ui button" id="submit" ng-click="addPayee()">
<i class="arrow right icon"></i>
</button>
</div>
</div>
<div class="search"></div>
<div class="payments" ng-controller="paymentController">
<li ng-repeat="newPayee in payees">{{payees}}</li>
</div>
<!-- <topbar></topbar> -->
</div>
(example template)
businessTemplate.html:
<div class="Business">
<div class="BusinessName" id="name">{{businessID}}</div>
<div class="Address" id="address">{{address}}</div>
<button class="ui icon button" id="hoverbox">
<i class="dollar icon"></i>
</button>
</div>
I ended up using a workaround with ng-repeat here. Still curious about the original question though.

Update page with items added via text field in Ember

I'm working on my first Ember app. It's a variation of a to do app. You type in a value, hit submission button and the page should update with each new item added using two-way data binding.
Every new item gets added to an array of object literals.
So adding new objects to the array and then looping through each item and printing it to the page is working just fine. Only problem is the page never updates with new items added via the input field.
I thought creating a custom view (App.ReRenderUserList in this instance) and adding .observes like they talk about in a previous question might be the answer, but that didn't seem to work.
Here's my code. Let me know if there's anything else I need to add. Thanks for your help.
index.html
<script type="text/x-handlebars" data-template-name="add">
{{partial "_masthead"}}
<section>
<div class="row">
<div class="column small-12 medium-9 medium-centered">
<form {{action "addToList" on="submit"}}>
<div class="row">
<div class="column small-8 medium-9 no-padding-right">
{{input type="text" value=itemName}}
</div>
<div class="column small-4 medium-3 no-padding-left">
{{input type="submit" value="Add +"}}
{{!-- clicking on this should add it to the page and let you keep writing --}}
</div>
</div>
<!-- /.row -->
</form>
</div>
<!-- /.column -->
</div>
<!-- /.row -->
</section>
<section>
<div class="row">
<div class="column small-12 medium-9 medium-centered">
<div class="list">
{{#each userItems}}
<div class="column small-16">
{{#view App.ReRenderUserList}}
<div class="item">{{name}}</div>
{{/view}}
</div>
<!-- /.column -->
{{/each}}
</div>
<!-- /.list -->
</div>
<!-- /.column -->
</div>
<!-- /.row -->
</section>
</script>
<!-- END add items template -->
pertinent app.js code:
var itemLibrary = [
{
'name' : 'bread'
},
{
'name' : 'milk'
},
{
'name' : 'eggs'
},
{
'name' : 'cereal'
}
];
var userLibrary = [];
App.AddRoute = Ember.Route.extend({
model: function() {
return Ember.RSVP.hash({
presetItems: itemLibrary,
userItems: userLibrary
});
}
});
App.AddController = Ember.ObjectController.extend({
actions: {
// add the clicked item to userLibrary JSON object
addToList: function(){
var value = this.get('itemName'); // gets text input value
userLibrary.push({
name: value // this is just echoing and not adding my new items from the form.
}); // adds it to JSON Object
console.log(userLibrary);
}
}
});
App.ReRenderUserList = Ember.View.extend({
submit: function(){
console.log('rerendered!');
}
});
You should use the pushObject method instead of the push method. This will update the bindings..
App.AddController = Ember.ObjectController.extend({
actions: {
// add the clicked item to userLibrary JSON object
addToList: function(){
var value = this.get('itemName'); // gets text input value
userLibrary.pushObject({
name: value // this is just echoing and not adding my new items from the form.
}); // adds it to JSON Object
console.log(userLibrary);
}
}
});

meteor display image with variable source

I'm using meteor.js and playing around with a simple application. I have a form on my page and once submitted the data is inserted into a database. I have a 'feed' of data on the left side of my page which updates when a new entry in the database is submitted, displaying the data. This is basic data at present about countries and populations etc. My question is how to mix a js variable to vary the source of an image file thats loaded in this 'feed' - hopefully explained below.
So, in code, I have this:
<template name="mainLeftCol">
<div class="col-sm-5">
{{> form}}
</div>
</template>
<template name="mainBody">
{{> mainLeftCol}}
<div class="col-sm-7">
{{#each dbEntry}}
{{> formItem}}
{{/each}}
</div>
</template>
and in a js file I have the event code for when the form is submitted:
Template.mainLeftCol.events({
'submit form': function(e) {
e.preventDefault()
var country = $(e.target).find('[id=country]').val()
prefix = country.slice(0,3);
if (prefix === 'Eng') {
console.log("Eng is for England");
}
var spot = {
country: country,
continent: $(e.target).find('[id=continent]').val(),
};
spot._id = Spots.insert(spot);
}
});
The formItems are being displayed using the following template which outputs the 'variables' that were input in the form:
<template name="formItem">
{{#Animate}}
<div class="panel panel-default spot animate">
<div class="panel-heading">
<h5 class="pull-right">{{country}}</h5>
<h4><mark><b>{{continent}}</b></mark></h4>
</div>
<div class="panel-body">
<img src="Eng.png" class="img-circle pull-right">
</div>
</div>
{{/Animate}}
</template>
As you can see in this template I have hardcoded "Eng.png" as the source for the image. What I would like to do is based on the prefix variable which slices the country field is to have the template display a different image (they're flags) based on the country on the template.
How can I mix a JS variable from my events code into the source of the image file in my template code?
Hope this makes sense!
I don't know if i got i right, but if you want to change the image (flag) according to the country try something like this:
Build a Template helper "prefix" which outputs the current country prefix.
Prefix helper:
Template.formItem.helpers({
countryPrefix: function () {
var country = $(e.target).find('[id=country]').val()
return country.slice(0,3);
}
});
In your Template you can now:
<div class="panel-body">
<img src="{{countryPrefix}}.png" class="img-circle pull-right">
</div>

Categories

Resources