Evaluate or call directive on click in angular - javascript

I am trying to load an image from json and if image is not available, then show firstname and lastname.
I have controller like this:
app.controller('task1Controller',['$scope', 'taskFactory', '$state', 'imageTestService', function($scope, taskFactory, $state, imageTestService){
$scope.taskData = {};
$scope.current = 0;
taskFactory.get().then(function(response){
$scope.jsonData = response.data.data.resultCareGivers;
});
$scope.back = function(){
$scope.current = ($scope.current !== 0 ? $scope.current - 1 : 0);
};
$scope.next = function(){
$scope.current = ($scope.current !== $scope.jsonData.length-1 ? $scope.current + 1 : $scope.jsonData.length-1);
};
}]);
and a Directive to verify image loading:
app.directive('imageTestDirective', function($http){
return {
restrict: 'A',
link: function($scope, elem, attrs){
attrs.$observe('ngSrc', function(ngSrc){
if(ngSrc != null && ngSrc != ""){
$http.get(ngSrc).then(function(success){
$scope.noImage = false;
console.log('success loading image', success);
}, function(error){
$scope.noImage = true;
console.log('error loading image', error);
});
}
});
}
};
});
Html with attribute directive and next and back button to cycle through json:
<img image-test-directive ng-show="noImage === false" ng-src="{{jsonData[current].profilepic}}" alt=""/>
<div ng-if="noImage">
<div>{{jsonData[current].firstName.charAt(1)+jsonData[current].lastName.charAt(1)}}</div>
</div>
<div class="col-xs-12">
<div class="col-xs-2">
<button type="button" ng-click="back()">Back</button>
</div>
<div class="col-xs-6" style="text-align: right">
<button type="button" ng-click="next()">Next</button>
</div>
</div>
The problem is the directive works on page load and the image is loaded properly, but I when I navigate through json object to view details, the directive is not evaluated (I mean when there no image inside json, it should show firstName+lastName)
How do I achieve it?

I think you wrote the logic too complicated for this use case.
In basic words JSON you get from Server contains some data with/without image URL or with broken image URL.
So instead to make HTML to be complicated, just embed your JSON in service and bring new JSON to your controller.
for example:
app.service('SomeService',['$q', /* ... */ function ($q /* ... */) {
function MyNewJSON(origJSON){
// check here if origJSON contains wrong image url
// and set new JSON key hasImage = true or false by validating it here in service and not in directive.
this.hasImage = true;
/* ... */
}
function getNewJSON(){
return new MyNewJSON(origJSON); // it might be promise and you need resolve it in controller
}
}]);
So your HTML should look like:
<img ng-if="stateData.hasImage" ng-src="stateData.profilepic" alt=""/>
<div ng-if="!stateData.hasImage">
<div >{{stateData.firstName.charAt(1)+stateData.lastName.charAt(1)}}</div>
</div>
No directive needed.
Since image validation can take some time, you can put default image (some kind of placeholder)

Related

AngularJS : Communication between directives - ng-repeat not refresh

I apologize of a mess but this is the first time on stackoverflow ;)
Link to jsfiddle
http://jsfiddle.net/1u1oujmu/19/
I have problem with communication between directives and refresh ng-repeat.
I have two pages homePage and dashboardPage - on these page I have directive when I refresh page (dashboardPage) everything is working, but when I switch on homePage and I will back to dahsboardPage my problem starts occurs.
Step reproduce:
dashboardPage - reload - add new link - list-link directive is refresh new link is on list
go to homePage
back to dashboard page
try to add new link - when link is added (on server and I receives response) I call factory to store a data:
dataFactory.editData("userLinksList", result.data);
//part of factory to edit and propagation data
editData: function(name, data){
dataArray[name] = data;
$rootScope.$broadcast(name);
},
Then in directive controller I have condition to listen propagation "userLinksList" checkRootScope this is flag for only one register listener
Problem is in line:
$scope.data.links = dataFactory.getData("userLinksList");
In $scope.data.links I receives new data but I don't know why ng-repeat is not refresh
when I go to homePage and back to dashboard new link will be on list
if(checkRootScope){
$rootScope.$on("userLinksList", function () {
$scope.data.links = dataFactory.getData("userLinksList");
});
checkRootScope = false;
}
homePage - on the page I have list-link directive:
<div class="columns marketing-grid">
<div class="col-md-6">
<list-link hp="true"></list-link>
</div>
</div>
dashboardPage - on the page I have this same directive without parameter:
<div class="row">
<div class="col-sm-12 col-md-8">
<list-link></list-link>
</div>
</div>
template of list-link:
<ul ng-if="data.links">
<li ng-repeat="link in data.links | filter: search" class="link-list-item" data-id="{{link.id}}">
<div class="row">
<div class="col-md-9">
<a ng-href="link.url"><h3>{{link.title}} <span>{{link.host}}</span></h3></a>
</div>
<div class="col-md-3 link-list-time text-right">
{{link.date | date : 'd/MM/yyyy' }}
</div>
<div class="col-md-12">
<blockquote ng-show="link.comment">{{link.comment}}</blockquote>
</div>
<div class="col-md-2">
<span class="link-list-counter all" title="Number of links">{{link.counterAll}}</span>
</div>
<div class="col-md-6 link-list-tags">
<span>tags:</span>
<ul ng-if="link.tags">
<li ng-repeat="item in link.tags">#{{item}}</li>
</ul>
</div>
<div class="col-md-4 text-right link-list-buttons">
<button class="btn btn-default btn-xs" title="Edit" ng-click="edit(link.id);">Edit <span class="glyphicon glyphicon-edit" aria-hidden="true"></span></button>
<button class="btn btn-default btn-xs" title="Delete" ng-click="delete(link.id);">Delete <span class="glyphicon glyphicon-remove" aria-hidden="true"></span></button>
</div>
</div>
</li>
</ul>
Directive list-link:
app.directive("listLink", ['path', function(path){
var path = path.url(),
checkRootScope = true;
return {
restrict : "E",
scope : {
hp : "="
},
templateUrl: path.template.listlink,
replace : true,
transclude : false,
controller : ['$rootScope', '$scope','conn', 'auth', 'loaderService','stringOperation','dataFactory', function($rootScope, $scope, conn, auth, loaderService, stringOperation,dataFactory){
var dataConenction = function(){
conn.getData(path.server.link, { params : $scope.data })
.then(function(result){
if($scope.data.all == true){
dataFactory.addData("popularLinksList",result.data);
$scope.data.links = dataFactory.getData("popularLinksList");
} else{
dataFactory.addData("userLinksList",result.data);
$scope.data.links = dataFactory.getData("userLinksList");
}
}, function(msg){
console.log(msg);
});
};
$scope.hp = (typeof $scope.hp === "undefined" ? false : $scope.hp);
$scope.path = path;
$scope.userInfo = auth.getUserInfo();
$scope.data = {
auth : $scope.userInfo,
check : false,
all : $scope.hp
};
dataConenction();
if(checkRootScope){
$rootScope.$on("userLinksList", function () {
$scope.data.links = dataFactory.getData("userLinksList");
});
checkRootScope = false;
}
$scope.edit = function(id){
$rootScope.$broadcast("editLink", {"id": id});
};
$scope.delete = function(id){
var check = confirm("Are you sure you want to remove?");
if (check == true) {
conn.deleteData(path.server.link, {"params" : {auth : $scope.userInfo, id : id}})
.then(function(result){
dataFactory.editData("userLinksList",result.data.links);
$scope.data.links = dataFactory.getData("userLinksList");
dataFactory.editData("userTagsList",result.data.tags);
}, function(msg){
console.log(msg);
});
}
};
}]
}
}]);
Not sure if you already fixed it but I had a crack at it.
First the "why not working" part -
Page1 creates a new scope, lets say scope1.
Page2 creates a new scope, say scope2.
When the Page1 is clicked the data.link is set to 5 items and below code is run [scope1.data.link = 5 items] -
if(checkRootScope){
$rootScope.$on("userLinksList", function () {
$scope.data.links = dataFactory.getData("userLinksList");
});
checkRootScope = false;
}
When the Page2 is clicked, it set 7 items to dataFactory and it is broadcasted to and $rootScope.on is executed to update scope2.data.links to 7 items. However scope2.data.links is still set to 5 items. This is because when $rootScope.on is executed first time the "$scope" variable within the "on" function refers to closure scope i.e scope1 and NOT scope2. So essentially when scope.data.links is set to 7 then scope.data.links is set to 7 and scope2.data.links is still set to 5.
Basically ng-view creates a new scope and if directive is part of each of the views, you would always end up having different data.link value in each of the views.
Solution:
You can fix it in two ways:
Option 1: You would be better off setting the value in scope as soon the promise is resolved instead of setting in factory and getting from it in $on listener. Atleast in this case.
http://plnkr.co/edit/IdrsO1OT9zDqdRiaSBho?p=preview
Option 2: If broadcast is really essentially I think you would have to bind the data.link to rootscope (which might not be a good practice).
http://plnkr.co/edit/VptbSKRf7crU3qqNyF3i?p=preview
and may be there are other options...

Reload a directive on controller event

I have a directive which is fetching data through ajax on load. But after an event in the controller which is posting some data, the Directive should re-compile with the new ajax data so that the changes can be reflected. Can you please help.
I have a compile function in the directive which takes data and puts that in HTML file and generates markup.
Then I have a save comment function in the controller which saves a new comment and so the directive gets the new data.
compile: function(tElement, tAttrs) {
var templateLoader = $http.get(base_url + 'test?ticket=' + $routeParams.ticketid, {cache: $templateCache})
.success(function(htmlComment) {
if (htmlComment != '')
tElement.html(htmlComment);
else
tElement.html('');
});
return function (scope, element, attrs) {
templateLoader.then(function (templateText) {
if (tElement.html() != '')
element.html($compile(tElement.html())(scope));
else
element.html('<div class="no-comments comment"><p>Be the first to comment</p></div>');
});
};
}
This is the compile part of the directive. I want this to be called through a normal controller event.
I would recommend #Riley Lark' response but as you already mentioned that your API returns an HTML instead of JSON, here is my take.
Your controller as:
<div ng-controller="MyCtrl">
<button ng-click="save()">Save Comment</button>
<comments></comments>
</div>
myApp.controller('MyCtrl', function($scope) {
$scope.commentHTML = '';
$scope.alert = function(salt) {
alert('You clicked, My Comment ' + salt);
}
$scope.save = function() {
// this imitates an AJAX call
var salt = Math.random(1000);
$scope.commentHTML+= '<div ng-click="alert(' + salt + ')">My Comment ' + salt + '</div>';
};
});
And the comments directive as:
myApp.directive('comments', function($compile) {
return {
restrict: 'E',
link: function(scope, element) {
scope.$watch(function() { return scope.commentHTML; }, function(newVal, oldVal) {
if (newVal && newVal !== oldVal) {
element.html(newVal);
$compile(element)(scope);
}
});
}
}
});
Hope this solves your problem..!
Working Demo
After you fetch the data you need, put the data in a $scope property. Define your template in terms of that property and it will automatically change when the data returns.
For example, your template might be
<div ng-repeat="comment in comments">
{{comment}}
</div>
You don't need a compile function or to "reload a directive" to accomplish this. The solution you posted is a sort of reimplementation of angular. It looks like you want to download a template with the data already interpolated into it, but Angular will help you the most if you separate the template from the data and let Angular interpolate it on the client.

Rendering unicode-utf-8 turkish characters with angular-js

Characters from a binded JSON text, Turkish the letters are shown with wrong encoding for eg. Özlem Güzelharcan which shall look like "özlem güzelharcan". I added <meta characters="utf-8"> in the head still no solution and there was no problem with laravel blade views.
If necessary this is how I get and use data:
view:
<div class="comment" ng-hide="loading" ng-repeat="comment in comments">
Comment #{{ comment.id }} </h3> <p>{{comment.title}}</p>
{{comment.author_id}} / {{comment.author.name}}
Services:
// public/js/services/commentService.js
angular.module('commentService', [])
.factory('Comment', function($http) {
var data = {
// get all the comments
get : function() {
return $http.get('/api/comments/');
}
}
console.log(data);
return data;
});
//controller (shortly)
.controller('mainController', function($scope, $http, Comment) {
// object to hold all the data for the new comment form
$scope.commentData = {};
// loading variable to show the spinning loading icon
$scope.loading = true;
// get all the comments first and bind it to the $scope.comments object
// use the function we created in our service
// GET ALL COMMENTS ====================================================
Comment.get()
.success(function(data) {
$scope.comments = data;
$scope.loading = false;
});
});
Which method is used to clean characters with AngularJS?
Thanks
Eventually, after trying many things, I discovered that you have to use ng-bind-html or ng-bind-html-unsafe (with ngSanitize) to get the correct encoding. Here is how it works in my view:
Comment #<span ng-bind-template="{{comment.id}}"></span> </h3>
<span ng-bind-html="comment.title "></span>
<p><div ng-bind-html="comment.content | truncate:25"></div></p>

Angular API calls and promises

I'm working on an angular app and having a difficult time with one seemly simple operation. Basically, I'm making a call to the soundcloud api, grabbing my tracks, then looping through those tracks and grabbing the iframe embed object, injecting that into the tracks object then sending that whole thing as a promise to be resolved and stored in a $scope.soundcloud object. Just fyi, the second SC call is necessary to generate the widget html. I wish it wasn't but it is hah.
This all happends as it should and i can see the object in $scope. My template picks up the initial data (main track data), and console.logging the object shows the track and embed data, but the template NEVER sees the embed data.
So, fundamentally, How do I get my template to see the embed data, so i can use it with a directive or ng-bind-html? Below is all my code, please ask if you need any more information! Thank you all very much.
HTML
<div class="track" ng-repeat="track in soundcloud.tracks">
<div class="front">
<img src="app/img/loading.gif" />
</div>
<div class="back" ng-bind-html="{{track.oembed}}">
</div>
</div>
Angular Service
getTracks: function(){
var deferred = $q.defer();
var promise = deferred.promise;
SC.get("/me/tracks", function(tracks){
$.each(tracks, function(k, v){
if(v.sharing != 'private'){
SC.oEmbed(v.uri, function(oembed){
v.oembed = $sce.trustAsHtml(oembed.html);
});
} else {
v.oembed = null;
}
});
deferred.resolve(tracks);
});
return $q.all({tracks: promise});
}
Angular Controller
.controller("GridCtrl", ['$scope', 'Soundcloud', function($scope, Soundcloud){
// Init the Soundcloud SDK config
Soundcloud.initialize();
// Get the tracks from soundcloud
Soundcloud.getTracks().then(function success(results){
// Store tracks in the $scope
$scope.soundcloud = results;
console.log(results);
});
}]);
Try creating a directive like this:
app.module('yourModule').directive('embedTrack', function() {
return function(scope, elem, attr) {
elem.replaceWith(scope.track.oembed);
};
});
You then use it like this:
<div class="track" ng-repeat="track in soundcloud.tracks">
<div class="front">
<img src="app/img/loading.gif" />
</div>
<div class="back">
<div embed-track></div>
</div>
</div>
In case you want to pass it as an attribute to the directive, you need to use attr.$observe to make sure you get the value after the interpolation.
<div embed-track={{ track.oembed }}></div>
The directive would then be:
app.module('yourModule').directive('embedTrack', function() {
return function(scope, elem, attr) {
attr.$observe('embedTrack', function(value) {
elem.replaceWith(value);
});
};
});

Populate jQuery UI accordion after AngularJS service call

I'm currently trying to build an AngularJS app where I'm using a jQuery UI accordion control.
The problem is, that the jQuery UI accordion is initiated before my AngularJS service is done loading data from the server. In other words: the accordion doesn't have any data when it's initiated and thus does not show when the data from AngularJS is populated.
The view looks like this:
<!-- Pretty standard accordion markup omitted -->
$("#b2b-line-accordion").togglepanels();
My AngularJS controller looks like this:
app.controller('orderController', function ($scope, orderService, userService) {
// Constructor for this controller
init();
function init() {
$scope.selected = {};
$scope.totalSum = 0.00;
$scope.shippingDate = "";
$scope.selectedShippingAddress = "";
$scope.orderComment = "";
$scope.agreements = false;
$scope.passwordResetSuccess = false;
$scope.passwordResetError = true;
userService.getCurrentUser(2).then(function (response) {
$scope.user = response.data;
orderService.getProductCategoriesWithProducts($scope.user).then(function (d) {
$scope.categories = d.data;
});
});
}
// Other methods omitted
});
And my AngularJS services looks like this:
app.service('orderService', function ($http) {
this.getProductCategoriesWithProducts = function (user) {
return $http.post('url to my service', user);
};
});
app.service('userService', function ($http) {
this.getCurrentUser = function(companyId) {
return $http.get('url to my service' + companyId + '.aspx');
};
this.resetPassword = function() {
return true;
};
});
Is there any way to tell the accordion to "wait" to initialise until the data is returned from the service? :-)
Thanks in advance!
Update
I tried chaining the methods and added some logging and it seems that the accordion is in fact initiated after the JSON is returned from the service.
userService.getCurrentUser(2).then(function(response) {
$scope.user = response.data;
}).then(function() {
orderService.getProductCategoriesWithProducts($scope.user).then(function(d) {
$scope.categories = d.data;
console.log("categories loaded");
}).then(function () {
$("#b2b-line-accordion").accordion();
console.log("accordion loaded");
});
});
However, it doesn't display the accordion :-( The first accordion div looks fine in the generated DOM:
<div id="b2b-line-accordion" class="ui-accordion ui-widget ui-helper-reset" role="tablist">
...
</div>
But the rest of the markup (which is databound with angular) itsn't initiated.
Complete markup:
<div id="b2b-line-accordion">
<div ng-repeat="productCategory in categories">
<h3>{{ productCategory.CategoryName }}</h3>
<div class="b2b-line-wrapper">
<table>
<tr>
<th>Betegnelse</th>
<th>Str.</th>
<th>Enhed</th>
<th>HF varenr.</th>
<th>Antal</th>
<th>Bemærkninger</th>
<th>Beløb</th>
</tr>
<tr ng-repeat="product in productCategory.Products">
<td>{{ product.ItemGroupName }}</td>
<td>{{ product.ItemAttribute }}</td>
<td>
<select ng-model="product.SelectedVariant"
ng-options="variant as variant.VariantUnit for variant in product.Variants"
ng-init="product.SelectedVariant = product.Variants[0]"
ng-change="calculateLinePrice(product); calculateTotalPrice();">
</select>
</td>
<td>{{ product.ItemNumber }}</td>
<td class="line-amount">
<span class="ensure-number-label" ng-show="product.IsNumOfSelectedItemsValid">Indtast venligst et tal</span>
<input type="number" class="line-amount" name="amount" min="0" ng-change="ensureNumber(product); calculateLinePrice(product); calculateTotalPrice();" ng-model="product.NumOfSelectedItems" value="{{ product.NumOfSelectedItems }}" />
<td>
<input type="text" name="line-comments" ng-model="product.UserComment" value="{{ product.UserComment }}" /></td>
<td><span class="line-sum">{{ product.LinePrice | currency:"" }}</span></td>
</tr>
</table>
</div>
</div>
</div>
SOLUTION
Finally I found a way around this! I'm not entirely sure if it's that pretty and if it's the Angular-way of doing stuff (I guess it isn't)
Made a directive with the following code:
app.directive('accordion', function () {
return {
restrict: 'A',
link: function ($scope, $element, attrs) {
$(document).ready(function () {
$scope.$watch('categories', function () {
if ($scope.categories != null) {
$element.accordion();
}
});
});
}
};
});
So basically when the DOM is ready and when the categories array changes (which it does when the data has been loaded), I'm initiating the jQuery UI accordion.
Thanks a lot t #Sgoldy for pointing me in the right direction here!
Yes you need a directive and you can handle this more angular way !
In HTML define the directive
<div ui-accordion="accordionData" ></div>
Return promise from your service and pass the promise to the directive.
In controller
$scope.accordionData = myService.getAccordionData();
The ui-accordion directive looks like
.directive('uiAccordion', function($timeout) {
return {
scope:{
myAccordionData: '=uiAccordion'
},
template: '<div ng-repeat="item in myData"><h3 ng-bind="item.title"></h3><div><p ng-bind="item.data"></p></div></div>',
link: function(scope, element) {
scope.myAccordionData.then(function(data) {
scope.myData = data;
generateAccordion();
});
var generateAccordion = function() {
$timeout(function() { //<--- used $timeout to make sure ng-repeat is REALLY finished
$(element).accordion({
header: "> div > h3"
});
});
}
}
}
})
When your service call succeed then you create your accordion. Here you can define your own accordion-template like
<div ng-repeat="item in myData">
<h3 ng-bind="item.title"></h3>
<div>
<p ng-bind="item.data"></p>
</div>
</div>
Template binds with your model data myData. I use ng-repeat inside the template to create accordion-header and accordion-body HTML.
In the generateAccordion method i use $timeout to make sure the ng-repeat is really finished rendering because $timeout will execute at the end of the current digest cycle.
Check the Demo
My best practice is to resolve your asynchronous services before controller is initiated.
As you can see in the document, http://docs.angularjs.org/api/ngRoute.$routeProvider
resolve - {Object.=} - An optional map of
dependencies which should be injected into the controller. If any of
these dependencies are promises, the router will wait for them all to
be resolved or one to be rejected before the controller is
instantiated. If all the promises are resolved successfully, the
values of the resolved promises are injected and $routeChangeSuccess
event is fired. If any of the promises are rejected the
$routeChangeError event is fired.
Your controller and view won't be even started before your service is resolved or rejected.
There is a good video tutorial about this, https://egghead.io/lessons/angularjs-resolve
In your case, you can config routes like the following
var myApp = angular.module('myApp', ['ngRoute']);
myApp.config(function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'main.html',
controller: orderController,
resolve: {
categories: function(orderService) {
return orderService.getProductCategoriesWithProducts();
},
user: function(userService) {
return userService.getCurrentUser();
}
}
});
Then, with your controller
app.controller('orderController', function($scope, categories, user) {
//categories and user is always here, so use it.
});
I have also found a similar question and answer here

Categories

Resources