AngularJS get external template and $compile - angularjs

I have an external template called _include.tmpl.html it's contents are:
<script id="sBlock1" type="text/ng-template">
<li ng-repeat="user in users" data-customer-id="{{user.CustomerID}}" ng-class-odd="'alternate'" ng-click="GetOrdersForUser($event)">
<span class="name">{{user.ContactName}}</span><br>
<span class="title">{{user.ContactTitle}}</span><br>
<span class="phone">{{user.Phone}}</span><br>
<span class="country">{{user.Country}}</span>
</li>
</script>
I would like to load the external template, feed it my array of users and get the compiled result? I was trying the below with no luck?
$http.get('_include.tmpl.html', { cache: $templateCache })
.then(function (response) {
var test = $compile(response.data)($scope.users);
console.log(test);
});
The use case is - for infinite scroll. You scroll down, I fetch results from a db feed the results to the template, get the compiled html and append that to the DOM. Each time you scroll down you get more results and the results keep getting appended to the DOM element.

You seem to be trying to mimic what a custom directive can already do for you
HTML
<users></users>
JS
angular.module('myApp').directive('users', function(){
return {
templateUrl:'_include.tmpl.html'
};
});
This will make the server side ajax call for you and populate the data. It will also store the template in $templateCache so another call to server isn't needed
However you would need to remove the wrapping script tag which is part of what is currently causing you problems

It should be $compile(response.data)($scope);.
And considering _include.tmpl.html template has been loaded, and sBlock1 is in template cache, it has to be
$http.get('sBlock1', { cache: $templateCache })
.then(function (response) {
var test = $compile(response.data)($scope);
console.log(test);
});

Related

use ng-bind-html with URL

Currently I have a div with ng-bind-html that I use to bind to HTML that I pass in
<div ng-bind-html="renderHtml(message.text)" />
Currently message.text is HTML. I would rather like to pass in a URL and have that HTML inserted in to the div.
How can I achieve that?
Personally, i would make a custom directive to do such a thing.
I would send the url as attribute paramater, make the directive fetch the html with $http.get(), and when its loaded, append it to the html.
You can add the source as:
<div ng-bind-html="URl | safeHtml"></div>
And need to add $sce for safe binding of the url with this directive:
app.filter('safeHtml', function ($sce) {
return function (val) {
return $sce.trustAsHtml(val);
};
});
Edit:
Rather than direct binding the url, embed it in iframe and use it for safe binding:
$scope.URL = <iframe ng-src="url"></iframe>
I would do it like this:
<input ng-model="myUrl"/>
<div id="myDiv" />
And then add a watch for myUrl, and make a request for the url each time it changes:
$scope.$watch('message.text', function(newValue) {
$.ajax({ url: 'newValue', success: function(data) {
$("#myDiv").html(data);
}});
}

AngularJS ng-style vs.style - ng-style does not refrest automatically

I have the following code to upload my profile image:
file.upload.then(function (response) {
$timeout(function () {
file.result = response.data;
vm.currentUser.profileImagePath = response.data.profileImagePath;
$scope.$apply();
});
}, function (re ...
and with this code the image is refreshed/reloaded after upload and works fine
<div class="userProfileItem userProfileImage" style="background-image: url(api/files/profileimage/{{vm.currentUser.profileImagePath}}/)">
except that I get sometimes the following Browser error:
403 Forbidden - http://localhost:8082/api/files/profileimage/%7B%7Bvm.currentUser.profileImagePath%7D%7D/"
Therefore I have changed code to this one at the bottom. But with the code at the bottom the image is not refreshed automatically.
<div class="userProfileItem userProfileImage" ng-style="{'background-image': 'url(api/files/profileimage/{{vm.currentUser.profileImagePath}}/)'}">
My question now would be how I can solve this issue?
You had {{}} interpolation inside ng-style expression, which is not required there. You could directly get access to scope variable there, use concatenation to form expression.
<div class="userProfileItem userProfileImage"
ng-style="{'background-image': 'url(api/files/profileimage/'+ vm.currentUser.profileImagePath +'/)'}">

Angularjs how can I reload the content

I have this code that loads the content when the page load,
Now I want to know how to reload the content by clicking the button.
Can you show me how to do it with example please?
Javascript code:
.controller('InterNewsCtrl', function($scope, NewsService) {
$scope.events = [];
$scope.getData = function() {
NewsService.getAll().then(function (response) {
$scope.events = response;
}), function (error) {
}
};
$scope.getData(); // load initial content.
})
Html code:
<ons-toolbar fixed-style>
<div class="left">
<ons-back-button>Voltar</ons-back-button>
</div>
<div class="right">
<ons-toolbar-button><ons-icon icon="ion-android-refresh"></ons-icon></ons-toolbar-button>
</div>
<div class="center">Internacional</div>
</ons-toolbar>
I think you're asking how to just retrieve new events from the backend. If that's correct, you don't need to reload the entire page.
You already have a function called getData which goes and retrieves you data via your service. Assuming your service doesn't cache the data, just call getData from your button:
<ons-toolbar-button ng-click="getData()"><ons-icon icon="ion-android-refresh"></ons-icon></ons-toolbar-button>
P.S. if you do explicitly have the cache set to true in your service, you can remove the cached data with $cacheFactory.get('$http').removeAll();.
For reloading same page in angular Js without post back
first remove that url from template cache if you call $route.reload() without removing it from $templateCache it will get it from cache and it will not get latest content
Try following code
$scope.getdata=function()
{
var currentPageTemplate = $route.current.templateUrl;
$templateCache.remove(currentPageTemplate);
$route.reload();
}
and Call it as following
<input type="button" ng-click="getdata();" value ="refresh"/>
Hope this will help
Please reffer this

In controller in angular js how to use console.log($window.result) to print data on screen

I am getting the data from javascript object using below method in another page.I want to use this data to print on html page using angular js....Below is snippet of code I am using.
app.controller('tableCtrl', function($scope,$http,$window) {
console.log($window.result);
});
But it is not working
Try
$window.document.write(result);
will overwrite current document and write your result
$window.document.write(result);
if you want it in any of you html page include below snippet
in Html
<div ng-controller="tableCtrl">
<span ng-bind="result"></span>
</div></code>
in tableCtrl
$scope.result = result; //whatever your result is

Refresh data on click outside controller in angular

I am trying to grasp the idea behind angular and ran into my first obstacle involving accessing data from outside the scope (the app?)
Here is a very simple example of what I'm trying to do:
HTML:
<div class=logo>
<a href='/refresh'>Refresh</a>
</div>
<div ng-app ng-controller="threadslist">
<div class='thread_list_header'>
<table class='thread_list_table'>
<tr class='table_header'>
<!--1--><td class='table_c1'></td>
<!--2--><td class='table_c2'>{{name}}</td>
<!--3--><td class='table_c3'>Cliq</td>
<!--4--><td class='table_c4'>Last Poster</td>
<!--5--><td class='table_c5'><a class="clickme">Refresh</a></td>
</tr></table>
</div>
<table class='thread_list_table' >
<tr class="thread_list_row" ng-repeat="user in users">
<!--1--><td class='table_options table_c1'></td>
<!--2--><td class='table_subject table_c2' title="">{{user.subject}}</td>
<!--3--><td class='table_cliq table_c3'></td>
<!--4--><td class='table_last table_c4'><span class="thread_username"><a href=#>{{user.username}}</a></span></td>
<!--5--><td class='table_reply table_c5'><abbr class="thread_timestamp timeago" title=""></abbr></td>
</tr>
</table>
</div>
JS:
function threadslist($scope, $http) {
$scope.name = 'Ricky';
// Initialising the variable.
$scope.users = [];
$http({
url: '/cliqforum/ajax/ang_thread',
method: "POST",
}).success(function (data) {
console.log(data);
$scope.users = data;
});
// Getting the list of users through ajax call.
$('.table_header').on('click', '.clickme', function(){
$http.get('/cliqforum/ajax/ang_thread').success(function(data){
$scope.users = data;
});
});
}
This is the part I can't figure out. My logo is supposed to clear whatever filter is on the current 'user' data. However, it sits outside the scope (and I imagine I shouldn't expand the scope to be the entire page?)
I have read something about scope.$spply but can't quite figure out what I'm supposed to do:
$('.logo').on('click', 'a', function() {
scope.$apply(function () {
$scope.users = data;
});
});
It's not quite necessary that I do it THIS way...I would just like to do what is correct!
Thanks!
and I imagine I shouldn't expand the scope to be the entire page?
Why not? That's definitely the way to do it. Just include the logo into the scope and you can then access it from your application, and use ng-click to add a click handler.
In fact, you should avoid using jQuery click handlers within your application. You could transform your JavaScript like so:
$scope.tableHeaderClick = function() {
$http.get('/cliqforum/ajax/ang_thread').success(function(data){
$scope.users = data;
});
});
Then update the HTML like so:
<tr class='table_header' ng-click="tableHeaderClick()">
it is an angular anti-pattern to include DOM elements in controller. you want to use the ng-click directive to respond to click events
see this plnkr:
http://plnkr.co/edit/KRyvifRYm5SMpbVvWNfc?p=preview

Resources