Angular JS / Ui router - Post Image URL in StateParams - javascript

I've a little issue : In my HomePage, I've an NG-repeat with image in post. When I want click in one post, I have this error :
TypeError: Cannot read property 'facebook' of undefined
at new <anonymous> (app.js:234)
at invoke (ionic.bundle.js:12877)
at Object.instantiate (ionic.bundle.js:12885)
at ionic.bundle.js:17154
at IonicModule.controller.self.appendViewElement (ionic.bundle.js:48176)
at Object.IonicModule.factory.ionicViewSwitcher.create.switcher.render (ionic.bundle.js:46392)
at Object.IonicModule.factory.ionicViewSwitcher.create.switcher.init (ionic.bundle.js:46312)
at IonicModule.controller.self.render (ionic.bundle.js:48050)
at IonicModule.controller.self.register (ionic.bundle.js:48008)
at updateView (ionic.bundle.js:53315)
AND
GET http://127.0.0.1:8103/%7B%7BauthData.facebook.cachedUserProfile.picture.data.url%7D%7D 404 (Not Found)
This is my HTML :
<div ng-repeat="(id,post) in posts">
<div class="card" ui-sref="tabpost({ postname: post.nameid, postdescription: post.descriptionid, postdate: post.startdateid, posthour: post.starthourid, postprice: post.priceid, postnbguest: post.nbguestid, postpicture: post.pictureid })">
<div class="item item-divider" ng-class="{{post.starthourid | setImageClass}}">
<h2 class="text stable"> {{ post.nameid }} </h2>
<h3 class="text stable" id="header-date">
<i class="icon ion-clock"></i> Le {{ post.startdateid | date : "d MMM" }} à {{ post.starthourid | date : "HH:mm" }}</p>
</div>
<div class="row">
<div class="col">
<h3><i class="icon ion-ios-location"></i> À 500m</h3></div>
<div class="col"><h3><i class="icon ion-ios-people">
</i> 2/{{ post.nbguestid }} </h3></div>
</div>
<button class="button button-stable" id="positive-btn-price" disabled>{{ post.priceid }}€</button>
<img class="imgProfilPostPositive" src="{{ post.userid.facebook.cachedUserProfile.picture.data.url }}">
<div class="item item-divider" id="footerPostNotepositive"><p> <i class="fa fa-star"></i> Popular </p> </div>
</div>
</div>
</div></div>
App JS :
.state('tabpost', {
url: '/tabpost/:postname/:postdescription/:postdate/:posthour/:postprice/:postnbguest/:postpicture',
templateUrl: 'templates/tab-post.html',
controller: 'PostCtrl',
})
Controller JS :
$scope.nameid = $stateParams.postname;
$scope.descriptionid = $stateParams.postdescription;
$scope.startdateid = $stateParams.postdate;
$scope.starthourid = $stateParams.posthour;
$scope.priceid = $stateParams.postprice;
$scope.nbguestid = $stateParams.postnbguest;
$scope.userid.facebook.cachedUserProfile.picture.data.url = $stateParams.postpicture;
How can I pass my picture in my Post page ?
Thanks for your time.

Using Angular markup like {{hash}} in a src attribute doesn't work right: The browser will fetch from the URL with the literal text {{hash}} until Angular replaces the expression inside {{hash}}. The ngSrc directive solves this problem.
The buggy way to write it:
<img src="http://www.gravatar.com/avatar/{{hash}}" alt="Description"/>
The correct way to write it:
<img ng-src="http://www.gravatar.com/avatar/{{hash}}" alt="Description" />
https://docs.angularjs.org/api/ng/directive/ngSrc

Related

Passing dynamic query params to anchor tag

I have following code
<ng-template #listItem let-itemData="data">
<div class="overlay-card">
<div class="card-header">
<span class="card-header-text"><i class="fas fa-user"></i></span>
<h3>{{ itemData.name }}</h3>
</div>
<div class="card-body">
<div class="card-body-text" *ngFor="let item of itemData.dataList">
<a [routerLink]="['/users']"
[queryParams]="{organizationId: item.organizationId, organizationName: item.organizationName, userId: item.id}"
[innerHTML]="item.name | highlight: searchText">{{ item.name }}</a>
</div>
</div>
<div class="card-footer">
<div class="button-container" *ngIf="formattedSearchData.users.length !== searchData?.users.length && formattedSearchData.users.length > 0"
(click)="loadMoreSearchData('users')">
<span class="load-button-text">Load</span> <span class="footer-number">({{ searchData?.users.length -
formattedSearchData.users.length }})</span>
</div>
</div>
</ng-template>
My question is in the part
<a [routerLink]="['/users']"
[queryParams]="{organizationId: item.organizationId, organizationName: item.organizationName, userId: item.id}"
[innerHTML]="item.name | highlight: searchText">{{ item.name }}</a>
can I pass dynamic [queryParams] something like
<a [routerLink]="{someDynamicValue}"
[queryParams]="{organizationId: item.organizationId, organizationName: item.organizationName, {someDynamicValue}: item.id}"
[innerHTML]="item.name | highlight: searchText">{{ item.name }}</a>
Note the places where I need Dynamic Values and if possible how.
I think you need to move the generating of queryParams out of your template like so:
this.someDynamicValue = 'user';
this.queryParamString = {
organizationId: 'organization.id',
organizationName: 'your own org name',
[this.someDynamicValue]: 1,
};
and then in your template:
<a [routerLink]="someDynamicValue"
[queryParams]="queryParamString"
[innerHTML]="item.name | highlight: searchText">{{ item.name }}</a>

Using background-image with ngStyle returns undefined

I try to add images (using API to load items) as background-image of element. But it keeps Cannot read property 'url' of undefined error. Though it actually renders url.
Here is the template side:
<div class="col s12 m4" *ngFor="let partner of partners">
<div class="card" *ngIf='partner'>
<div class="card-image " [ngStyle]="{'background-image': 'url(' + partner?.photo['url'] + ')'}">
<a class=" btn-floating halfway-fab waves-effect waves-light blue left ">
<i class="material-icons ">shopping_cart</i>
</a>
<a class="btn-floating halfway-fab red " [routerLink]='"/dashboard/partners/edit/"+partner["id"]'>
<i class="large material-icons ">mode_edit</i>
</a>
</div>
<div class="card-content ">
<h5 class="center font-weight-400 ">{{partner.name}}</h5>
<p class="center ">{{partner.category.name}}</p>
</div>
</div>
</div>
and controller:
export class PartnersListComponent implements OnInit {
partners: {}[] = [];
constructor(private _partnersService: PartnersService) {}
ngOnInit() {
this._partnersService.getPartners().subscribe(data => {
if (data.status == "200") {
this.partners = data.data;
}
});
}
}
Example data:
category:'',
created_at:"2017-12-27 12:57:50",
deleted_at:null,
first_entry:1,
id:1,
name:"Zara",
photo:{id: 5, url: "example.jpeg"},
updated_at:"2017-12-27 12:57:50",
username:"zara-001"
According to the error message, the photo field is not defined for at least one partner. You can protect against that situation with the elvis operator:
[ngStyle]="{'background-image': `url(${partner?.photo?.url})`}"
or
[style.background-image]="`url(${partner?.photo?.url})`"

Why value in directive does not get updated - Angular Js?

I just encounter a problem I have written a directive but its not getting update, I dont know why, in console it does change but in directive it does not.
Here is my directive
mainControllers.directive('mallsproduct', function () {
return {
restrict: 'E',
scope: {
productInfo: '=info',
linkid: '=linkid'
},
templateUrl: 'directives/dashboard_product.html'
};
});
Here is my `html`
<div class="aa-properties-content-body mg-7" ng-controller="DashboardController as ctrl">
<ul class="aa-properties-nav aa-list-view">
<li style="border: 1px solid #ccc;margin-bottom: 25px;" ng-repeat="active_products in productInfo.items">
<article class="aa-properties-item mg-top-0-notimp">
<a class="aa-properties-item-img" href="#/product/{{active_products.id}}">
<img ng-if="active_products.photos[0].path" resize-image alt="img" class="" src="{{active_products.photos[0].path}}">
<img ng-if="!active_products.photos[0].path" resize-image class="" src="img/default_product.jpg" alt="">
</a>
<div class="aa-properties-item-content">
<div class="aa-properties-about padding-0-notimp">
<h5>{{active_products.name| limitTo : 10}}{{active_products.name.length > 10 ? '...' : ''}}</h5>
<p class="font-size-11-imp"><i class="fa fa-building-o" aria-hidden="true"></i> {{active_products.mall.name| limitTo : 10}}{{active_products.mall.name.length > 10 ? '...' : ''}}</p>
<p class="font-size-11-imp"><i class="fa fa-map-marker" aria-hidden="true"></i> {{active_products.mall.address| limitTo : 10}}{{active_products.mall.address.length > 10 ? '...' : ''}}</p>
<p class="font-size-11-imp"><i class="fa fa-phone" aria-hidden="true"></i> {{active_products.shop.telephone}}</p>
<p class="font-size-11-imp" ng-if="linkid == 3"><i class="fa fa-eye" aria-hidden="true"></i> {{active_products.views}}</p>
<div class="modal-demo">
<script type="text/ng-template" id="myModalContent.html">
<div ng-include src="'partials/update_product.html'"></div>
</script>
<div ng-controller="AddProductController">
<button ng-click="view_product(active_products.id)"><i class="fa fa-pencil" aria-hidden="true"></i></button>
<button ng-click="del_product(active_products.id)"><i class="fa fa-trash-o" aria-hidden="true"></i></button>
<button ng-if="linkid == 2" ng-init="status = 1" ng-click="reactivate_product(active_products.id, status)"><i class="fa fa-lock" aria-hidden="true"></i></button>
</div>
<div class="modal-parent">
</div>
</div>
</div>
</div>
</article>
</li>
</ul>
<div class="aa-title pad-top-30" ng-if="linkid == 1">
<p>Global page count for active product is {{global_pagecount}} and active product count from API is {{productInfo._meta.pageCount}}</p>
<h3 ng-if="global_pagecount < productInfo._meta.pageCount" class="text-align-center color-feroz cursor-pointer" ng-click="load_more(global_pagecount, linkid)">{{$root.translated_labels.dashboard.load_more}}</h3>
</div>
<div class="aa-title pad-top-30" ng-if="linkid == 3">
<p>Global page count for most viewed is {{global_pagecount_mostv}} and most viewed count from API is {{productInfo._meta.pageCount}}</p>
<h3 ng-if="global_pagecount_mostv < productInfo._meta.pageCount" class="text-align-center color-feroz cursor-pointer" ng-click="load_more(global_pagecount_mostv, linkid)">{{$root.translated_labels.dashboard.load_more}}</h3>
</div>
</div>
I am including directive in dashboard partial like this
<div class="active tab-pane" ng-if="linkid === '1'">
<malls-product info="active_products" linkid="linkid"></malls-product>
</div>
<!--Active products list ends here -->
<!-- Get Inactive Products -->
<div class="active tab-pane" ng-if="linkid === '2'" >
<malls-product info="$root.inactive_products" linkid="linkid"></malls-product>
</div>
<!--Get Inactive products ends here -->
<div class="active tab-pane" ng-if="linkid === '3'" >
<malls-product info="$root.mostviewed_products" linkid="linkid"></malls-product>
</div>
<!-- View Profile-->
and This is the api which does show the result in console.
$scope.global_pagecount = 1;
$scope.active_product = function () {
$http.get($rootScope.baseurl + 'abc?&page=' + $scope.global_pagecount,
{headers:
{'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': $rootScope.keyword_auth_token, 'Accept-Language': $cookies.get('type')}
})
.success(function (data) {
//$scope.active_product_pageCount = data._meta.pageCount;
if ($scope.global_pagecount === 1) //I know for sure the first page of pagination is 1
{
$scope.active_products = data;
}
if ($scope.global_pagecount > 1) // If user click load more global count gets incremented and new results push in active_producst
{
/* for loading new results Pagination Applied */
for (var times = data.items.length - 1; times >= 0; times--) {
$scope.active_products.items.push(data.items[times]);
}
}
console.log($scope.active_products);
})
.error(function (data) {
// console.log(data);
});
};
What is the issue, why it is not getting update, If I use rootscopethen it works fine, obviously it has too, but not with $scope.
Note : when scope.global_pagecount value is equal to 2 i get new results but not in directive only in console. By default scope.global_pagecount has value equal to 1.
You don't use your directive correctly. You define it as:
mainControllers.directive('mallsproduct'
Which means you should use it as:
<mallsproduct ..>
Or define your directive camelcased:
mainControllers.directive('mallsProduct'
Then you can use it as you do now:
<malls-product ..>
This is because of the Isolated scope doesn’t know anything about its parent scope. You just created a directive with an isolated scope.
To access any parent scope data, we need to pass the scope data to our directive explicitly. This is achieved by setting properties on the scope object in the DDO.
Another important thing is that, these properties also MUST be set as the attributes of the directive html element.

Short HTML Code from Json will display the HTML code instead of the rendered version

I'm retrieving an array filled with user data. They should be displayed in a ul. One of the fields is the prefix for every user as an html code like this <span class="red-text">[Admin]</span>. But when I try to append the li element it renders the html code instead of the red version of the span.
My json code:
{
"users":[
{
"id":"1",
"usrname":"YannickFelix",
"email":"example#gmail.com",
"lvl":"4",
"prefix":"<span class=\"red-text\">[Admin]<\/span>"
}
]
}
And my javascript:
listElemTmplt = `
<li class="collection-item avatar">
<i class="material-icons circle {"{{color}}"}">person</i>
<span class="title">{"{{usrname}}"}</span>
<p>{"{{prefix}}"} {"{{usrname}}"} | {"{{email}}"}
</p>
<span class="secondary-content">
<a class="waves-effect waves-circle" href="users.php?action=edit&uID={"{{id}}"}">
<i class="material-icons grey-text text-darken-1">create</i>
</a>
<a class="waves-effect waves-circle waves-red modal-trigger" href="#modal{"{{id}}"}">
<i class="material-icons grey-text text-darken-1">delete</i>
</a>
</span>
<div id="modal{"{{id}}"}" class="modal">
<div class="modal-content black-text">
<h4>Löschen</h4>
<p>Möchtest Du den Benutzer "{"{{usrname}}"}" wirklich löschen?</p>
</div>
<div class="modal-footer">
Abbrechen
Löschen
</div>
</div>
</li>
`;
template = Handlebars.compile(listElemTmplt);
finishedString = [];
$.getJSON("**url**", function (data) {
console.log(data);
$("ul#users").html("");
data["users"].forEach(function (element, index, array) {
html = template({"{"}id: element["id"], usrname: element["usrname"], email: element["email"], prefix: element["prefix"]{"}"});
$("ul#users").append(html);
});
});
The example item in the List. [Admin] should be red and without the html code
Handlebars escapes the values you give to it when using {{prefix}}. When you want to use raw HTML you have to use {{{prefix}}} to tell it not to escape it.

Angular ng-click function populates table?

So I have these boxes that show minimal info for an array created using an ng-repeat. There could be 1 and 10 items returned with objects and their properties These boxes are clickable and when clicked, should populate the table. Problem is, I keep getting a reference error and for the likes of me, cannot see why. The function is defined and should call and fill the table based on the Id of the box to fill the table with more info. The array object is called "swipe".
My html for the the boxes:
<div class="swipeBoxes" ng-repeat="swipe in swipes">
<a href="" ng-click="editSwipe(swipe.id)" >
<div class="swipeBox col-md-12">
<div class="col-md-12 claimObject">
<span class="claimLine" style="width: 3px; position: absolute; top: 5px; left: 5px;">{{ $index + 1 }}.</span>
<span class="claimedLeft">swipe date:</span>
<span class="claimedRight">{{ swipe.date | date: 'MM/dd/yyyy'}}</span>
</div>
<div class="col-md-12 claimObject">
<span class="claimedLeft">provider:</span
><span class="claimedRight">{{ swipe.merchant }}</span>
</div>
<div class="col-md-12 claimObject">
<span class="claimedLeft">amount:</span>
<span class="claimedRight">{{ swipe.amount | currency }}</span>
</div>
</div>
</a>
</div>
My target table that should be filled with data once one of the objects are selected from above:
<div class="swipeDetails col-md-12">
<div class="swipeFlexHead col-md-12">
<p>Swipe Details</p>
</div>
<div class="swipeFlexHead2 col-md-12">
<p>{{ swipe.merchant }}</p>
</div>
<div class="col-md-12">
<div class="swipeFlexElement col-md-4">
<p>Swipe Date</p>
<p>{{ swipe.date | date: 'MM/dd/yyyy' }}</p>
</div>
<div class="swipeFlexElement col-md-4">
<p>Status</p>
<p>{{ swipe.status }}</p>
</div>
<div class="swipeFlexElement col-md-4">
<p>Card Used</p>
<p>{{ swipe.cardHolder }} {{ swipe.cardUsed }}</p>
</div>
</div>
<div class="col-md-12">
<div class="swipeFlexElement col-md-4">
<p>Swipe Amount</p>
<p>{{ swipe.amount | currency }}</p>
</div>
<div class="swipeFlexElement col-md-4">
<p>Amount Requiring Documentation</p>
<p>{{ swipe.reqAmount | currency }}</p>
</div>
<div class="swipeFlexElement col-md-4">
<p>Documentation Due Date</p>
<p>{{ swipe.dueDate | date: 'MM/dd/yyyy' }}</p>
</div>
</div>
</div>
And finally, my controller for this that is pulling data and has the 'editSwipe' function:
app.controller('swipeController', ['$scope', 'swipesService', '$location', 'Upload', '$timeout', '$filter', 'utilsService',
function ($scope, swipesService, $location, Upload, $timeout, $filter, utilsService) {
$scope.swipes = [];
$scope.swipeFormSubmitted = false;
swipesService.getSwipes().then(function (results) {
$scope.swipes = results.data;
});
$scope.swipe = {
id: '',
descr: '',
merchant: '',
date: '',
amount: '',
reqAmount: '',
status: '',
cardUsed: '',
cardHolder: '',
dueDate: ''
}
$scope.editSwipe = function(id) {
$scope.swipeInfo = angular.copy(swipe);
};
}]);
In your editSwipe function you are not doing anything with id. With angular.copy(swipe) you are using swipe which is not defined. I guess you want to copy the swipe you've clicked, then you need to do
ng-click="editSwipe(swipe)"
$scope.editSwipe = function(swipe) {
$scope.swipe = angular.copy(swipe); // I don't see where you use swipeInfo?
};
BTW: is there any need to deep copy the swipe? Can't you just pass the reference $scope.swipe = swipe;

Categories