Doopler Doopler - 6 months ago 14
HTML Question

How to pass a firebase data into a function

I am trying to pass string into function that is in my javascript file

The variable {{data.title}} is accessible elsewhere in my html file but it seems I am missing something because the function is not receiving the variable as ''

<a class="item item-icon-left" ng-click="favorites('{{data.title}}')">
<i class="icon ion-ios-star-outline"></i>
<span>Add to favorites</span>
</a>


JS File:

$scope.favorites = function (x) {
console.log(x);
// retrieve it (Or create a blank array if there isn't any info saved yet),
var favorites = JSON.parse(localStorage.getItem('favoritesInfo')) || [];;
// add to it,
favorites.push({ name: x});
// then put it back.
localStorage.setItem('favoritesInfo', JSON.stringify(favorites));
console.log(localStorage.getItem('favoritesInfo'));
}

Answer

The ng-click directive expects an expression. You passed in a string with what you believed to be an interpolation.

You can only use interpolation ({{ the return value of an expression/variable }}) in templates, not in expressions.

So the right thing to do is ng-click="favorites(data.title)".

Using expressions in HTML templates

Generally, when doing expressions inside an HTML template in AngularJS, you can access your scope variables as you usually would, without the $scope prefix.

So if in your controller you have something like this:

$scope.title = 'News From Today';

You can bind to it (expressions, right?) like so:

<h1 ng-bind="title"></h1>

Or via interpolation like so:

<h1>{{ title }}</h1>

Comments