How to bind to object in repeat.for with Aurelia - javascript

I am currently trying to create a custom element with a bindable property and bind to that property to the variable of a repeat.for loop. This seems like it should be a simple task but I cannot get it to work and am wondering if it perhaps has to do with the variable being an object. The code for my custom element is below:
game-card.js
import { bindable } from 'aurelia-framework';
export class GameCard {
#bindable gameData = null;
#bindable name = '';
bind() {
console.log('card-game-data: ' + JSON.stringify(this.gameData, null, 2));
console.log('name: ' + this.name);
}
}
game-card.html
<template>
<div class="card medium">
<h3 class="center-align left">${gameData.name}</h3>
<div class="right-align right">${gameData.isPublic}</div>
</div>
</template>
The view that is using the custom element is below:
<template>
<require from="./game-card"></require>
<div>
<div class="row">
<div repeat.for="game of games">
<game-card class="col s6 m4 l3" gameData.bind="game" name.bind="game.name"></game-card>
</div>
</div>
</div>
</template>
The games object looks as follows:
[{name: 'SomeName', isPublic: true}, {name: 'AnotherName', isPublic: false}]
Now, when I run the code, the console.log statements in the game-card.js bind method print out undefined for the gameData, but prints out the correct name of the game for the console.log('name: ' + this.name) statement. I can't figure out why the binding is working when I bind to a property of the game object, but not when I bind to the game object itself. Any help would be greatly appreciated, thank you so much!

You have to write game-data.bind instead of gameData.bind. From the first look, this should be the only problem

Related

Run function when element was created

I have some elements created by v-for. How can I run the function only once by keeping 'for every element creation' as a condition .
<div v-for"value in values">
<div # function(value, domElement) if value.bool===true #>
</div>
the easiest way, IMO, would be to make each of those elements a Vue Component & pass the function down as a prop.
File One
<div v-for="value in values">
<Custom-Component :propValue="value" :propFunction="functionYouNeed" />
</div>
Custom Component
<template>
<div> {{propValue.value}} </div>
</template>
<script>
export default {
props: ['propFunction', 'propValue'],
created(){
if (this.propValue.bool === true) {
this.propFunction()
}
}
}
</script>
It's not so clear what exactly you want:
<div # function(value, domElement) if value.bool===true #>
So, here's all possible solutions you want to implement.
You can bind the method using once modifier:
<div #click.once="yourMethod">
Or, if you want not to change the content then you can use v-once:
<div v-once>{{ neverChanged }}</div>
But if you just need to use the function when it was created then call the function inside created property and do not bind the method anywhere else.
created() {
if(condition) {
this.yourMethod()
}
}

Two way bindings trigger 10 digest() iteration reached

I have some problems with angular binding and I'm not very experienced with it. I will post all questions here as they are related.
Here is some angularjs code snipped that triggers 10 digest() cycle reached. I found some similar posts and the cause is that a change is performed recursively in digest(), but I cannot find the cause in my example.
Here is code:
<work-timekeepings-day timekeepings="dailyTimekeepingCtrl.timekeepingList | timekeepingDay : dailyTimekeepingCtrl.selectedDay" day="dailyTimekeepingCtrl.selectedDay"></work-timekeepings-day>
Component:
var workTimekeepingsDay = TimekeepingsApp.component('workTimekeepingsDay', {
templateUrl : 'angular/components/work-timekeepings-day.html',
controllerAs: '$workTkDayCtrl',
bindings : {
timekeepings : '=',
day: '='
}
});
HTML template:
<div class="row lightgreen-row padding-5 border-rounded" ng-repeat-start="workTk in $workTkDayCtrl.timekeepings">
<div class="col-md-4"> <b> {{ workTk.user.firstName + ' ' + workTk.user.lastName }} </b> </div> </div> ...
Filter function:
var timekeepingDayFilter = TimekeepingsApp.filter('timekeepingDay', function() {
return function(timekeepings, filterDay) {
var result=[];
angular.forEach(timekeepings, function(timekeeping) {
var timekeepingDay = moment(timekeeping.workDay);
if (timekeepingDay.isSame(filterDay, 'day')) {
result.push(timekeeping);
}
});
return result;
}
});
If I apply filter function inside HTML template it doesn't trigger the error, but the two-way binding with 'day' variable seems to not work properly. If I update 'dailyTimekeepingCtrl.selectedDay' in another component, bound in the same way, the change is not reflected in workTimekeepingsDay component.
Here is the filter applied in component template:
<work-timekeepings-day timekeepings="dailyTimekeepingCtrl.timekeepingList" day="dailyTimekeepingCtrl.selectedDay"></work-timekeepings-day>
<div class="row lightgreen-row padding-5 border-rounded" ng-repeat-start="workTk in $workTkDayCtrl.timekeepings | timekeepingDay : day">
<div class="col-md-4"> <b> {{ workTk.user.firstName + ' ' + workTk.user.lastName }} </b> </div> </div> ..
Q1: Why is the 'digest() aborted' error occur if I am not updating the base array? How can I pass directly the filtered array to component in timekeepings variable?
Q2: Why is day variable not updated in component if dailyTimekeepingCtrl.selectedDay is updated?
I solved this by using lodash memoize function to use result from cash. Although I'd have preferred to not use an external library, but to change the algorithm, I am still happy with this.

Angular JS data binding in component is not working

I am using Angular JS 1.5.6 components to build dynamically a form. The hierarchy is the following : index.html calls component my-view which calls component my-form which calls unitary components like inputs and button.
The issue is that the data binding is not working because any modification in input components is not taken into account into my-view component.
Besides I have a weird behavior, each time I update input value, a call is made to view component function.
I have plunkered this, the submit button triggers console.log (so need to open firebug to see it in action).
Here is my index.html
<body ng-app="MyApp">
<my-view></my-view>
</body>
Here is myView.html
<div class="container">
<h2>With component myform</h2>
<my-form form-elements="
[{type:'input', label:'First name', placeholder:'Enter first name',model:$ctrl.userData.firstName, id:'firstName'},
{type:'input', label:'Last name', placeholder:'Enter last name',model:$ctrl.userData.lastName, id:'lastName'},
{type:'button', label:'Submit', click:$ctrl.click()}]"></my-form>
</div>
<div class="container">
<h2>Check data binding</h2>
<label>{{$ctrl.userData.firstName}}</label>
<label>{{$ctrl.userData.lastName}}</label>
</div>
Here is myView.js
(function() {
'use strict';
angular.module('MyApp').component('myView', {
templateUrl: 'myView.html',
controller: MyViewController,
bindings: {
viewFormElements: '<'
}
});
function MyViewController() {
this.userData = {
firstName: 'François',
lastName: 'Xavier'
};
function click() {
console.log("Hello " + this.userData.firstName + " " + this.userData.lastName);
}
this.click = click;
}
})();
I manage to solve my issue with 2 way binding and by putting form-element in an object instead of putting it directly in the view ($ctrl.formElements). It is on plunker.
myView.html
<div class="container">
<h2>With component myform</h2>
<my-form form-elements=$ctrl.formElements></my-form>
</div>
<div class="container">
<h2>Check data binding</h2>
<label>{{$ctrl.formElements}}</label><br />
</div>'

Angular 2: TypeError: l_thing0 is undefined in [{{thing.title}} in AppComponent#4:44]

I'm getting a strange error in my app. It's supposed to print out {{thing.title}} from an object, but it shows an error in the console:
EXCEPTION: TypeError: l_thing0 is undefined in [{{thing.title}} in AppComponent#4:44]
I'm not sure where l_thing0 is coming from. If I try to show {{thing}}in the page, it displays [object Object]. If I try to JSON.stringify(this.thing) (see the showObj() function), it correctly displays the stringified object. But if I try to access an attribute like {{thing.title}} I get the error that l_thing0 is undefined.
Here is app.component.ts:
import {Component, OnInit} from 'angular2/core';
import {Thing} from './thing';
import {ThingService} from './thing.service';
import {SubThingComponent} from "./subthing.component";
#Component({
selector: 'thing-app',
template: `
<div class="container">
<div class="row">
<div class="col-md-12">
<h1>{{thing.title}} Show Stringified Obj</h1>
<subthing></subthing>
</div>
</div>
</div>
`,
styles:[`
`],
directives: [SubThingComponent],
providers: [ThingService]
})
export class AppComponent implements OnInit {
constructor(private _thingService: ThingService) { }
public thing: Thing;
showObj() {
// This correctly shows the stringified object
alert(JSON.stringify(this.thing));
}
getThing() {
this._thingService.getThing().then(thing => this.thing = thing);
// This correctly logs the object
setTimeout(() => {console.log('thing', this.thing)}, 5000);
}
ngOnInit() {
this.getThing();
}
}
Any ideas?
The issue is that the first time you load the page, thing is still undefined, it gets set to its real value later on asyncronously, so the first time it tries to access the property, it will throw an exception. The ? elvis operator is a shortcut to a nullcheck:
{{thing?.title}}
But its usually a best idea more performant not even try to render the component at all until you have the real object by adding something like:
<h1 *ngIf="thing">
to the container.
though I am coming late to the party but thought this might help for those who're using Angular 5.
Strangely noticed the elvis operator will not work in *ngFor loop, but works for *ngif. So here's my code to address the issue.
<div *ngIf = "fullObject?.objProperty">
<h1>{{fullObject.objProperty1}}</h1>
<div *ngFor = "let o of fullObject.objPropertyArray">
<h3>{{o._subheader}}</h3>
<p>
{{o._subtext}}
</p>
</div>
</div>
</div>
You could also set a new variable isFinished to false before retrieving data from server or async function and after receiving the data set it to true. Then put isFinished variable in *ngIf to check if server/function process is done?
I am using Angular 8 and although the data is shown, I also had this error and googling it brought me to this question. The accepted answer (though well explained) did not solve it for me. (Maybe because of a newer version, or the use with *ngFor)
It does not suffice to just use *ngIf, as you can see:
throws error: v1
<div class="row">
<pre>
<li *ngFor="let obj of object.content">{{obj | json}}</li>
</pre>
</div>
throws error: v2
<div class="row" *ngIf="object.content">
<pre>
<li *ngFor="let obj of object.content">{{obj | json}}</li>
</pre>
</div>
throws error: v3
<div class="row" *ngIf="object.content">
<pre>
<li *ngFor="let obj of object?.content">{{obj | json}}</li>
</pre>
</div>
no error: v1
<div class="row">
<pre>
<li *ngFor="let obj of object?.content">{{obj | json}}</li>
</pre>
</div>
no error: v2
<div class="row" *ngIf="object?.content">
<pre>
<li *ngFor="let obj of object.content">{{obj | json}}</li>
</pre>
</div>
no error: v3
<div class="row" *ngIf="object?.content">
<pre>
<li *ngFor="let obj of object?.content">{{obj | json}}</li>
</pre>
</div>

How to access functions of a controller from within another controller via scope?

I have the following problem, I want to call a function of another controller from within a controller I want to use for a guided tour (I'm using ngJoyRide for the tour). The function I want to call in the other controller is so to say a translator (LanguageController), which fetches a string from a database according to the key given as parameter. The LanguageController will, if the key is not found, return an error that the string could not be fetched from the database. In my index.html fetching the string works, but I want to use it in the overlay element of my guided tour, which does not work, but only shows the "not fetched yet"-error of the LanguageController.
My index.html looks like this:
<body>
<div class="container-fluid col-md-10 col-md-offset-1" ng-controller="LangCtrl as lc" >
<div ng-controller="UserCtrl as uc" mail='#email' firstname='#firstname'>
<div ng-controller="GuidedTourCtrl as gtc">
<div ng-joy-ride="startJoyRide" config="config" on-finish="onFinish()" on-skip="onFinish()">
...
{{lc.getTerm('system_lang_edit')}}
...
</div>
</div>
</div>
</div>
</body>
The controller I'm using for the guided Tour looks like this:
guidedTourModule.controller('GuidedTourCtrl',['$scope', function($scope) {
$scope.startJoyRide = false;
this.start = function () {
$scope.startJoyRide = true;
}
$scope.config = [
{
type: "title",
...
},
{
type: "element",
selector: "#groups",
heading: "heading",
text: " <div id='title-text' class='col-md-12'>\
<span class='main-text'>"\
+ $scope.lc.getTerm('system_navi_messages') + "\
text text text text\
</span>\
<br/>\
<br/>\
</div>",
placement: "right",
scroll: true,
attachToBody: true
}
];
...
}]);
And the output I ultimately get looks like this for the overlay element:
<div class="row">
<div id="pop-over-text" class="col-md-12">
<div id='title-text' class='col-md-12'>
<span class='main-text'>
not fetched yet: system_navi_messages
text text text text
</span>
<br/>
<br/>
</div>
</div>
</div>
...
I hope someone can see the error in my code. Thanks in advance!
Things needs clarity are,
How you defined the 'getTerm' function in your Language controller, either by using this.getTerm() or $scope.getTerm(). Since you are using alias name you will be having this.getTerm in Language controller.
Reason why you are able to access the getTerm function in your overlay element is, since this overlay element is inside the parent controller(Language Controller) and you are referencing it with alias name 'lc' while calling the getTerm function. Thats' why it is accessible.
But the string you pass as a parameter is not reachable to the parent controller. that's why the error message is rendered in the overlay HTML.
Please make a plunker of your app, so that will be helpful to answer your problem.

Categories

Resources