Pass value to a function in ng-init - javascript

I want to repeat data using div and in this div , I have one more repeatation using id value from first repeatation. So I want to pass this value using function in ng-init but got me error.
<div ng-controller="ProductsCtrl" ng-init="getData()">
<div class="col-sm-12" ng-repeat="data in form">
<div class="card">
<div class="card-header">
<h4>{{data.title}}</h4>
</div>
<div class="card-block">
<div class="row" ng-init="getImages({{data.id}})">
<div class="form-group col-sm-3" ng-repeat="image in images">
<figure>
<img ng-src="{{imgURL}}/{{image.file_name}}" width="220" height="176">
<figcaption>Fig.1 - A view of the pulpit rock in Norway.</figcaption><br />
<label>Description : {{image.remarks}}</label><br />
Read More . .
</figure>
</div>
</div>
</div>
<div class="card-footer">
<h4>{{data.description}}</h4>
</div>
</div>
</div>
</div>
So, how can I pass {{data.id}} in ng-init="getImages({{data.id}})"? If I put value ng-init="getImages(15)" then, item will appear.
file.js
$scope.getImages = function (id2) {
$http.get(commonData.apiURL + 'product/detailsImage.php?id='+id2)
.success(function (data) {
$scope.images = data;
//console.log(JSON.stringify(data));
})
.error(function (data, status, headers, config) {
$scope.errorMessage = "Couldn't load the list of Orders, error # " + status;
console.log("error");
});
}

You need to keep one thing in mind, If you are want your angular code to work on html page, use {{}}. And you do not need these curly braces if you are writing the code with the angular attributes... It means if something is already part of angularjs, you need not to use curly braces.
To solve this issue, you need to replace the below line
<div class="row" ng-init="getImages({{data.id}})">
with this following line
<div class="row" ng-init="getImages(data.id)">

You do not need annotations {{}}
ng-init="getImages(data)
and then inside the controller
$scope.getImages = function(data){
console.log(data.id);
}

Related

JS function Cant get the Value from vbhtml

How can I get value from my html action link, I tried to set the value in js function and it is work, and the problem is js not get the value form html file, and this forloop only the first one will call the Javascript function.
this is my js function
function selectTemplate() {
$('#choose').on('click', function () {
var objTemplate = $(".styTemplate").val();
$.post(strRoot + "/Home/Index/", { styTemplate: objTemplate });
});
};
and this is my vbhtml code
#For Each item In Model
Dim currentItem = item
'<!-- single-awesome-project start -->
#<div Class="col-md-4 col-sm-4 col-xs-12 #Html.DisplayFor(Function(modelItem) currentItem.strTemplateType)">
<div Class="single-awesome-project">
<div Class="awesome-img">
<img src="#Url.Content("~/Content/TemplateCSS/img/portfolio/" & currentItem.strTemplateType & ".jpg")" alt="" />
<div Class="add-actions text-center">
<div Class="project-dec">
<a Class="venobox" data-gall="myGallery" href="#Url.Content("~/Content/TemplateCSS/img/portfolio/" & currentItem.strTemplateType & ".jpg")">
<h4>#currentItem.strTemplateName</h4>
<span> Web Development</span>
#Html.ActionLink("Choose", "companyInfomation", "Home", New With {.id = "choose"}, New With {.styTemplate = currentItem.strTemplateName})
</a>
</div>
</div>
</div>
</div>
</div>
'<!-- single-awesome-project end -->
Next
</div>
<script>
selectTemplate();
</script>
Maybe it's better to use onclick attribute? Use this instead of Html.ActionLink:
Choose

My single page application which is implemented using AngularJS is taking long time to load the page

I am working on the Single page application and using AngularJS. In my application, all DOM elements get loads using ajax and due to this I have used number of ng-repeat and binding expression and this is the reason my page is taking long time to load the page. Please help to solve my issue.
app
angular.module('tabApp', []);
Service
angular.module('tabApp')
.service('mrcService', ['$http', function($http) {
this.categories = [];
this.getCategories = function() {
return $http({
method: "GET",
url: 'mrcdata.aspx'
}).success(function(data) {
categories = data;
return categories;
});
};
}]);
Controller
angular.module('tabApp')
.controller('dynamicContentCtrl', ['$scope', 'mrcService', function($scope, mrcService) {
$scope.categories = [];
mrcService.getCategories().then(function(response) {
$scope.categories = response.data.Categories;
});
}]);
HTML code
<div class="main-content container" ng-controller="dynamicContentCtrl">
<div ng-controller="desktopTabCtrl" class="row desktop-content">
<div class="col-md-3 col-sm-4 category-items">
<nav class="nav categories-nav">
<ul class="categories">
<li ng-repeat="category in categories" class="category" ng-class="{ active: isSet(category.CategoryRank) }">
<a href="javascript:void(0)" ng-click="setTab(category.CategoryRank)" class="text">
<span>{{category.CategoryTitle}}</span>
</a>
<span class="arrow-right"></span>
</li>
<li class="category static">
<C5:LocalLiteral runat="server" Text="mrc.home.learnmoretab"/>
</li>
</ul>
</nav>
</div>
<div class="col-md-9 col-sm-8 document-tiles">
<div ng-repeat="category in categories" ng-show="isSet(category.CategoryRank)" class="tile-container">
<div class="row">
<div ng-repeat="document in category.Documents" class="col-md-6 col-sm-6 tile">
<div class="tile-content row">
<div class="col-md-12 col-sm-12">
<div class="thumbNail-content col-md-6 col-sm-6">
<p class="title">{{document.DocumentTitle}}</p>
<p class="audience">{{document.Audience}}</p>
</div>
<div class="thumbNail-image col-md-6 col-sm-6">
<img alt="Thumb Nail" src="{{document.ThumbnailUrl}}">
</div>
</div>
<div class="col-md-12 col-sm-12">
<div class="download-section">
<select class="lang-dropdwn"
ng-model="document.DefaultDialectId"
ng-change="selectLang(document , document.LocalizedDocuments , document.DefaultDialectId )">
<option ng-repeat="localizedDocument in document.LocalizedDocuments"
value="{{localizedDocument.DialectId}}">
{{localizedDocument.LanguageName}}
</option>
</select>
</div>
<div class="button-conatiner" ng-init="document.DownloadLink = document.DocumentId +':'+document.DefaultLocalizedDocumentId">
<a class="button" href="documentdownloader.aspx?documentid={{document.DownloadLink}}"><C5:LocalLiteral runat="server" Text="basket.esddelivery"/></a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
Here's a few options you can try to improve performance.
1. You should set the track by in the ng-repeats
To minimize creation of DOM elements, ngRepeat uses a function to "keep track" of all items in the collection and their corresponding DOM elements. For example, if an item is added to the collection, ngRepeat will know that all other items already have DOM elements, and will not re-render them.
The default tracking function (which tracks items by their identity) does not allow duplicate items in arrays. This is because when there are duplicates, it is not possible to maintain a one-to-one mapping between collection items and DOM elements.
If you do need to repeat duplicate items, you can substitute the default tracking behavior with your own using the track by expression.
For example, you may track items by the index of each item in the collection, using the special scope property $index.
Example:
<div ng-repeat="item in items track by $index">{{item.name}}</div>
2. You could use one way data binding to items you know wont be changed. This will disable the watchers for those items and improve performance. Example:
Instead of this
{{item.name}}
Use this
{{::item.name}}
Please remember that this is a one way binding and these values will not be updated if something changes in your scope but you will need to manually update it.
3. Try to limit the ng-show and ng-hide attributes since this will add more watchers and leads to poor performance.

Handlebars.js returns empty markup

I have a problem with rendering handlebars.js template. I'm doing AJAX request to server, and servers returns me data which contains 'dishes' array with objects.Dish object contains id,price,weight,description,and array of photos. Then i render it with handlebars,and its works properly, 'html' variable containts rendered markup.
var data ;
var modalDishInfo;
var modalDishComments;
var vitrina;
function ajax(params){
$.ajax({
url: '/admin/getDishByCategory',
type: 'POST',
dataType: "json",
data: params,
success: function (result){
data = JSON.parse(result);
vitrina = Handlebars.compile( $('#vitrina_template').html() );
modalDishInfo = Handlebars.compile( $('#modalDishInfo').html() );
var html = vitrina(data.dishes);
console.log(html);
$('.foodmenucontent').empty();
$('.foodmenucontent').append(vitrina(data.dishes));
}
<script id="vitrina_template" type="text/x-handlebars-template">
{{#each this}}
<div class="col-lg-3 mealcard" >
<p class="text-center mealname">{{ dish_name }}</p>
<div class="weightandprice">
<div class="weightcontainer"><span class="mealweight pull-right">{{ dish_weight }} грамм</span></div>
<div class="pricecontainer"><span class="mealprice pull-left">{{ dish_price }} руб.</span></div>
</div>
<button class="orderbutton center-block">ЗАКАЗАТЬ</button>
</div>
{{/each}}
</script>
As you can see this code renders elements, which contains links with openModal() function.I have empty bootstrap modal window and want to render its content, according to clicked link.
function openModal(id){
var foo = id.slice(-1);
var modaldata = data.dishes;
var modaldish = $.grep(modaldata, function (element) {
return element.id == foo;
});
modaldish = modaldish[0];
console.log(modaldish);
var markup = modalDishInfo(modaldish);
$('#modalDishInfo').empty();
$('#modalDishInfo').append(markup);
$('#modalDish').modal('show');
$('.fotorama').fotorama();
};
and template
<script id="modalDishInfo" type="text/x-handlebars-template">
<div class="modalcontainer">
<div class="row">
<div class="col-lg-6">
<div class="fotorama" data-nav="thumbs" data-width="100%" data- thumbwidth="80" data-thumbheight="45"
data-transition="crossfade" data-loop="true" data-keyboard="true" data-navposition="bottom"
data-fit="cover" data-ratio="1600/900">
{{#each dish_photos}}
<img src="/uploads/gallery/{{ this.path }}" class="img-responsive" alt="">
{{/each}}
</div>
</div>
<div class="col-lg-6">
<p class="mealname">{{ dish_name}}</p>
<pre>{{ dish_description }}</pre>
<p>{{ dish_weight }}гр.</p>
<p class="mealprice">{{ dish_price }}руб.</p><br>
<button class="orderbutton ">ЗАКАЗАТЬ</button>
</div>
</div>
The problem is second template(modalDishInfo) dont want to render, console.log returns 'markup' variable completely empty. I tried different combinations of block helpers, and expressions,but none of them working. Maybe im missing something important? Or need to use specific expressions, when passing single object to template?
I found mistake that i did.My template id and container id(which is empty) are the same. So jquery selector returned me empty markup. I didn't notice that, because im using TWIG and my scripts was in {% verbatim %} tag to avoid TWIG errors, so i dont receive any errors or warning using duplicate ID's in code. Hope my answer is informative and can be helpful to someone.

Can i retain old value of scope and update some other value to other div in AngualrJS

Well,I'll try to explain my approach why I am doing this. I have trimmed the code for the sake of simplicity. I want to create one div where there should be <h4>BroadCategory Name</h4> and below this headline, I am calling one API to fetch some images associated with that BroadCategory Name
<div ng-controller="NavigationController">
<div ng-repeat="primaryItems in categories">
<div>
<h4><span>{{primaryItems.BroadCategory}}</span></h4>
</div>
<div ng-init="getImgForCategory(this.primaryItems)">
<div ng-repeat="ad in ads">
{{ ad.ad_type }}
<a ng-href="#productList/{{primaryItems.BroadCategory}}">
<img src="{{ ad.images[0] }}" >
</a>
</div>
</div>
</div>
</div>
My Controller:
$http.get("/get_categories/")
.success(function(response){
$scope.categories = response;
})
.error(function (msg) {
console.log(msg);
});
$scope.getImgForCategory = function (categoryInfo) {
var category = (categoryInfo.BroadCategory);
$http.get('/Some_API_ad_type='+category) //API to fetch some images associated with that **BroadCategory**
.success(function (response) {
$scope.ads = response;
})
.error(function (msg) {
console.log(msg);
})
}
Issue : Issue is that $scope.ads keeps the value of last called API response and so the {{ ad.ad_type }} and similar ads attributes have all the same values (which is the response for the last BroadCategory name)
How can I resolve this with best Angular approach?
<h1>Expected Output: </h1>
<h4>BroadCategory1</h4>
BC1_data1
<br>BC1_data2
<h4>BroadCategory2</h4>
BC2_data1
<br>BC2_data2
<h1>Actual Output: </h1>
<h4>BroadCategory1</h4>
BC2_data1
<br>BC2_data2
<h4>BroadCategory1</h4>
BC2_data1
<br>BC2_data2
Well, the generated html in your inner ng-repeat all use the same $scope.ads list. So if that gets updated, all data on your screen will just show the new value of $scope.ads.
What I would do is link the adds to the category. Like the following:
$scope.getImgForCategory = function (categoryInfo) {
var category = (categoryInfo.BroadCategory);
$http.get('/Some_API_ad_type='+category)
.success(function (response) {
categoryInfo.ads = response;
})
.error(function (msg) {
console.log(msg);
})
}
.
<div ng-controller="NavigationController">
<div ng-repeat="primaryItems in categories">
<div>
<h4><span>{{primaryItems.BroadCategory}}</span></h4>
</div>
<div ng-init="getImgForCategory(primaryItems)">
<div ng-repeat="ad in primaryItems.ads">
{{ ad.ad_type }}
<a ng-href="#productList/{{primaryItems.BroadCategory}}">
<img src="{{ ad.images[0] }}" >
</a>
</div>
</div>

Template is compiled before the result is returenf from $http service

Hi I am trying to retrieve data from the server using $http, and correct data is being retrieved from the service, the data is -
[{
"URL":"someimg.jpg",
"TITLE":"Test Demo",
"DATE_ADDED":"2014-02-08 00:46:00",
"SUMMARY":"this is summary"
}]
the template that I wrote is as follows -
<article class="span8" ng-controller="allBlogs">
<div ng-show="success">
<div ng-repeat="blog in blogs.data">
<div class="row">
<div class="span3">
<img ng-src="{{blog['URL']}}" alt="" />
</div>
<div class="span5" ng-repeat-end>
<h4>{{blog.TITLE}}</h4>
<p>{{blog.DATE_ADDED}}</p>
<p>{{blog.SUMMARY}}</p>
</div>
</div>
</div >
</div>
</article>
the controller for the above template is as follows -
pk.controller("allBlogs", function($scope, $http, BlogsHandler){
$scope.success = false;
(function(){
BlogsHandler.getAllBlogs().success(function(data){
console.log(data);
$scope.success = true;
$scope.blogs = data.data;
});
})();
});
I am trying to set the success as true when the service returns data and thus the remaining part of the template should run. But this is not happening. Is it not that any change to $scope variable is being watched by the framework itself?
Help needed. I even tried with ng-switch with no effect.
Thanks
You assign data.data to $scope.blogs, so you don't need to add .data before blogs again.
$scope.blogs = data.data;
So, try this:
<div ng-repeat="blog in blogs track by $index">
<div class="row">
<div class="span3">
<img ng-src="{{blog.URL}}" alt="" />
</div>
<div class="span5">
<h4>{{blog.TITLE}}</h4>
<p>{{blog.DATE_ADDED}}</p>
<p>{{blog.SUMMARY}}</p>
</div>
</div>
</div >

Categories

Resources