Angular template mysteriously shows only certain {{expressions}} - javascript

I'm using Angular JS v. 1.2.26 and I've spent hours trying to figure out why I cannot get certain expressions to appear in the view.
A complete, minimal, example is below (or jsfiddle here):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script type="text/javascript">
var screen_id = '430732';
</script>
<script type="text/javascript" src="/public/scripts/vendor/angular.min.js"></script>
<script>
var tsApp = angular.module('tsApp',[]);
var screenCtrl = tsApp.controller('screenCtrl', function($scope) {
$scope.columns = [null,[null,{"name":"","id":"583","column":1,"order":1,"display_class":"static-text","block_agency":"static-text","block_mode":"static-text","custom_param":"","custom_body":"<b>This demo screen is brought to you by TransitScreen.com</b>"},{"name":"U St NW+ 17th St NW","id":"591","column":1,"order":2,"display_class":"masstransit","block_agency":"metrobus","block_mode":"bus","stops":[{"agency":"metrobus","mode":"bus","name":"U St NW+ 17th St NW","vehicles":[{"agency":"metrobus","mode":"bus","name":"U St Nw + 17th St Nw","full_route":"96","short_route":"96","destination":"Capitol Heights Station","predictions":[9,42],"direction":"Eastbound","vehicle_number":0,"logo":"","display_route":"96","longname":"96","route_class":"bus_metrobus","destination_class":"bus_metrobus","longname_accessible":null,"prediction1":9,"prediction2":42,"units":"MINUTES"},{"agency":"metrobus","mode":"bus","name":"U St Nw + 17th St Nw","full_route":"90","short_route":"90","destination":"Anacostia Station","predictions":[10,39],"direction":"Southbound","vehicle_number":1,"logo":"","display_route":"90","longname":"90","route_class":"bus_metrobus","destination_class":"bus_metrobus","longname_accessible":null,"prediction1":10,"prediction2":39,"units":"MINUTES"}],"walk_directions":"","walk_minutes":null,"arrow_svg":null}]}]];
});//end screenCtrl
screenCtrl.$inject = ['$scope'];
</script>
</head>
<body class="screen-body total-cols-1" ng-app="tsApp">
<div class="page-holder" ng-controller="screenCtrl">
<div class="col" id="col-1">
<div ng-repeat="block in columns[1]">
<div ng-include="'/public/scripts/block.html'"></div>
</div>
</div>
</div>
</body>
</html>
Here is the contents of block.html:
<div ng-switch on="block.display_class">
<div ng-switch-when="masstransit">
<table>
<div ng-repeat="stop in block.stops">
<div ng-repeat="vehicle in stop.vehicles">
<h2>Test 1</h2>
{{ stop.mode }}
{{ block.display_class }}
{{ vehicle.vehicle_number }}
<tr class="" id="">
<td class="">
<h2>Test 2</h2>
{{ stop.mode }}
{{ block.display_class }}
{{ vehicle.vehicle_number }}
</td>
</tr>
</div><!-- ng-repeat -->
</div><!-- ng-repeat -->
</table>
</div>
</div><!-- end ng-switch -->
Which outputs this...
Test 1 shows the expected values twice (because there are two items in the loop). Then in Test 2 there is only one iteration and only the middle value appears.

The problem is not identified in your code above. There is nothing wrong with ng-repeat in a TR or TD. It is more likely something is wrong in your controller or somewhere else in your code.
I created a jsfiddle which shows an example of displaying data as near the data structure in your question as I could guess. It works fine.
<table ng-controller="myCtrl" border=1>
<tr ng-repeat="stop in block.stops">
<td ng-repeat="vehicle in stop.vehicles">
<dl>
<dt>Mode:</dt><dd>{{ stop.mode }}</dd>
<dt>Class:</dt><dd>{{ block.display_class }}</dd>
<dt>Number:</dt><dd>{{ vehicle.vehicle_number }}</dd>
</dl>
</td>
</tr>
</table>
EDIT
I fixed your jsfiddle to work. See edit 2 here You can't expect Angular to work properly on malformed HTML. You cannot wrap TRs in DIVs like that. Even if Angular works who knows how some browsers might treat it. You might have data popping out after the table. Table rendering is one of the parts of HTML that is fairly strict.

Related

Using ng-if to check angular variable from another directive in angularjs

I am new to angular. I have a task to display json data in specific design, but I have not idea about nesting of json. Is it possible to check if the data is json or an array of json and then display the output.
Here I am trying to display data only if it is an array. But it is not working. Kindly help.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp">
<div ng-controller="readJson as rj">
<div ng-repeat="d in rj.data">
<ul>
<div ng-model="myVar" ng-init="myVar = "{{isArray(d.third)}}>
<div ng-if="myVar">
<li>{{d.third}}</li>
</div>
</ul>
</div>
</div>
</div>
</body>
<script>
(function(){
var app=angular.module('myApp',[]);
app.controller('readJson',function($scope){
$scope.isArray = angular.isArray;
this.data=[{"first":"one","second":"two","third":"three"},
{"first":"ONE","second":"two","third":"three"},
{"first":"onE","second":"two","third":
[
{"first":"1one","second":"2two","third":"3three"},
{"first":"1ONE","second":"2two","third":"3three"}
]}];
});
})();
</script>
</html>
Here you go. This example will display data only when "third" param is an array.
https://plnkr.co/edit/EX0BvcYrLPFbiN2ezlqQ
<div ng-repeat="d in data">
<ul>
<div ng-init="myVar = isArray(d.third)"></div>
<div ng-if="myVar">
<li>{{d.third}}</li>
</div>
</ul>
</div>
The problem was in ng-init="myVar = "{{isArray(d.third)}} - you need to make sure isArray(d.third) is in expression (between "") and there is no need to use {{}} syntax within ng-init directive. It will evaluate expression for you (check an example).

Ng-repeat functionality doesnt work

Today is my first day with Angular.js , and I stuck at a basic controller :
my APP.js
(function()
{ var app = angular.module('store', [ ] );
app.controller('StoreController', function()
{
this.product = gem;
});
var gem = [
{name:'John', price:25, description:'boy',soldout: false,canpurchase:true},
{name:'Kohn', price:25, description:'boy',soldout: false,canpurchase:true}
]
//not mentioned:false
})();
Index.HTML
<!DOCTYPE html>
<html ng-app="store">
<script src="js/angular.min.js" type="text/javascript"></script>
<link href="css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
<title>Purple</title>
</head>
<body ng-controller = "StoreController as store">
<script src="js/app.js" type="text/javascript"></script>
<h1>{{"Create your CV"}}</h1>
<div ng-repeat="products in store.product">
<div ng-hide="store.product.soldout">
<h1> {{store.product.name}} </h1>
<h2><em class="pull-right">{{store.product.price | currency}}</em></h2>
<h3> {{store.product.description}} </h3>
<button ng-show = "store.product.canpurchase"> Add to cart </button>
</div>
</div></body></html>
My code is working fine , but NG - repeat is not working, if I don't choose ng-repeat and display each item as an array then I am getting a display but not with "ng-repeat" .. Any idea's what am I missing ?
Please dont mark this as negative, I have done a lot of research before asking this question
Code on fiddle : http://jsfiddle.net/68Dkz/2/
Here is working version using controller alias store as shown. Note that product was changed to products in controller since the array contains more than one product. I think you are gtting confused about which is array and which is the individual item within the ng-repeat due to this
<div ng-repeat="product in store.products">
<div ng-hide="product.soldout">
<h1> {{product.name}} </h1>
<h2><em class="pull-right">{{store.product.price | currency}}</em></h2>
<h3> {{product.description}} </h3>
<button ng-show="product.canpurchase">Add to cart</button>
</div>
</div>
DEMO
store is your module not your scope you don't need it in the iteration, do products in product instead
<div ng-repeat="products in product">
<div ng-hide="products.soldout">
<h1> {{products.name}} </h1>
<h2><em class="pull-right">{{products.price | currency}}</em></h2>
<h3> {{products.description}} </h3>
<button ng-show = "products.canpurchase"> Add to cart </button>
</div>
</div>
stop aliasing your controller, it is unnecessary and may cause issues with the html compiler
using products as your iterator is confusing, I would suggest making the collection products and the iterator product

angularjs accordion load data when opening

We are making use of the angularjs accordion, however, our accordion is fairly big, and contains a lot of data.
What we are looking at doing is loading the data when the accordion opens. ie dont render the internal content, until a user click on the accordion header.
Below is how we are using the accordion at the moment:-
<accordion close-others="false">
<accordion-group heading="{{result.ReceivedDateTime}}{{result.OrderName}}" ng-repeat="result in resultsbyorder">
<table id="tbl" class="table table-striped table-bordered" ng-repeat="Grid in result.Results">
<tr ng-repeat="item in Grid" ng-show="$first">
<th ng-repeat="somat in item">
{{somat.ColumnHeader}}
</th>
</tr>
<tr ng-repeat="item in Grid">
<td ng-repeat="somat in item">
{{somat.ColumnValue}}
</td>
</tr>
</table>
</accordion-group>
</accordion>
as a side note, is it possible to only render the accordion headers that are displayed on the screen, then render the remaining on scrolling?
I think what you are better off doing is to compile it once when it is opened the first time.
That way, you don't have to compile the same content again, even though it was compiled before the last time the accordion group was opened.
Over the top of my head, I can think of using the ng-switch directive. As you must be aware, this directive allows to display DOM elements conditionally, based on the case variable.
However, where this directive differs from the ng-show or ng-hide directive is that the contents within the case statement are not compiled until the corresponding case variable is matched.
Thus, what you could do is have the following setup in your HTML document:
<accordion close-others="oneAtATime">
<accordion-group is-open="isopen">
<accordion-heading>
Accordion Heading
</accordion-heading>
<div ng-switch on="isopen">
<div ng-switch-when="true">
<!-- Content that should be compiled when the accordion is opened
goes here -->
</div>
</div>
</accordion-group>
</accordion>
A demonstration of the same can be found in this plunkr.
Also, I believe ng-if directive also achieves the same effect. So, you can use either of the directives to achieve your requirements.
I am doing this very thing at the moment and have found that Angular likes using a collection (even if it's just a single element) to make the accordion, to wit if you do, you can bind the is-open to an element on that group and then setup a watch on that group in the controller. Consider the following (think of putting an ajax call to get your data instead of logging to console):
var ngtestapp = angular.module("ngtestapp", ['ui.bootstrap']);
ngtestapp.controller("ngTestController", function ($scope) {
$scope.userComments = [
{
RowId: 123,
DateCreated: new Date(2015, 1, 2, 0, 0, 0, 0),
CreatedBy: 564,
Message: 'Carpe Dieum',
CreatedByDisplayName: 'Daniel Graham'
},
{
RowId: 124,
DateCreated: new Date(2015, 1, 5, 0, 0, 0, 0),
CreatedBy: 562,
Message: 'That was awesome',
CreatedByDisplayName: 'Peter Griffin'
}
];
$scope.feedbackGroup = [{ title: "User Comments", open: false }];
$scope.$watch('feedbackGroup', function (feedbackGroup) {
if (feedbackGroup[0].open) {
console.log("opened feedback group.");
} else {
console.log("closed feedback group.");
}
}, true);
$scope.userTaskNote = "user task test note";
});
.nav, .pagination, .carousel, .panel-title a { cursor: pointer; }
<html lang="en" ng-app="ngtestapp">
<head>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.12.1/ui-bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.12.1/ui-bootstrap-tpls.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
</head>
<body>
<div ng-controller="ngTestController">
<div class="container-fluid">
<accordion close-others="true">
<accordion-group ng-repeat="group in feedbackGroup" heading="{{group.title}}" is-open="group.open">
<ul class="list-group">
<li class="list-group-item" ng-repeat="comment in userComments track by $index | orderBy:comment.DateCreated">
<span class="badge" ng-bind="comment.DateCreated | date:'shortDate'"></span>
<strong ng-bind="comment.CreatedByDisplayName">Username</strong> <p ng-bind="comment.Message">comment</p>
</li>
</ul>
</accordion-group>
<accordion-group is-open="false" heading="Other">
<textarea class="form-control input-sm" ng-model="userTaskNote" placeholder="Add a task note here..."></textarea>
</accordion-group>
</accordion>
</div>
</div>
</body>
</html>

Handlebars.js Conditional Statement

I am trying to execute a conditional statement in my Handlebars template. The issue is it is not rendering the content at all if an if condition is inserted.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>Handlebars.js example</title>
</head>
<body>
<div id="placeholder">This will get replaced by handlebars.js</div>
<script type="text/javascript" src="handlebars.js"></script>
<script id="myTemplate" type="text/x-handlebars-template">
{{#names}}
<div style="width:100%;border:2px solid red;">
<table style="width:100%;border:2px solid black">
<tr>
<td style="width:50%; border:2px solid yellow;">
<img src="{{itemImage}}"></img>
</td>
<td style="width:50%; border:2px solid green;">
<img src="btn_downloadAudio.png"></img><br><br>
<img src="btn_downloadPresentation.png"></img><br><br>
<img src="btn_downloadTranscript.png"></img><br><br>
<img src="btn_downloadVideo.png"></img><br><br>
</td>
</tr>
<tr>
<td colspan="2"><img src="{{itemType}}">
<label style="font-weight:bolder">{{itemTitle}}</label>
</td>
</tr>
<tr>
<td colspan="2">
<p>{{itemDescription}}</p>
</td>
</tr>
</table>
</div>
{{/names}}
</script>
<script type="text/javascript">
var source = document.getElementById("myTemplate").innerHTML;
var template = Handlebars.compile(source);
//alert(template);
var data = {
names: [
{ "itemImage": "authorImage.png",
"itemTitle": "Handlebars.js Templating for HTML",
"itemType": "icon_document.png",
"isAudioAvailable": "true",
"isPresentationAvailable": "true",
"isTranscriptAvailable": "true",
"isVideoAvailable": "false",
"itemDescription": "Rendeting HTML content using Javascript is always messy! Why? The HTML to be rendered is unreadable. Its too complex to manage. And - The WORST PART: It does it again and again and again! Loss: Performance, Memory, the DOM has to be re-drawn again each and every time a tag is added."}
]
};
document.getElementById("placeholder").innerHTML = template(data);
</script>
</body>
</html>
CONDITION: Display Video Button if the isVideoAvailable is true
Any help is appreciated.
Thanks,
Ankit
If you want something to be displayed conditionally, you use an {{#if}}:
{{#if isVideoAvailable}}
<img src="btn_downloadVideo.png"><br><br>
{{/if}}
Of course for that to work properly, your data should make sense and isVideoAvailable should be a boolean value. So you'll also need to clean up your data to make sense and isVideoAvailable should be true or false rather than the strings 'true' or 'false'; preprocessing your data is quite common with Handlebars so fixing your data would be the best thing to do, fixing your data would also let you use it in a natural manner in JavaScript.
Demo: http://jsfiddle.net/ambiguous/LjFr4/
But, if you insist on leaving your boolean values as strings then you could add an if_eq helper and say:
{{#if_eq isVideoAvailable "true"}}
<img src="btn_downloadVideo.png"><br><br>
{{/if_eq}}
Cleaning up your data would be a better idea.

Angular.js view doesn't update when nested $scope array is updated

I am trying to make an angular.js view update itself when adding a comment. My code is as follows:
<div class="comment clearfix" data-ng-repeat="comment in currentItem.comments" data-ng-class="{bubble: $first}" data-ng-instant>
<div>
<p>
<span class="username">{{comment.user}}</span> {{comment.message}}
</p>
<p class="time">
10 minutes ago
</p>
</div>
</div>
<div class="comment reply">
<div class="row-fluid">
<div class="span1">
<img src="assets/img/samples/user2.jpg" alt="user2" />
</div>
<div class="span11">
<textarea class="input-block-level addComment" type="text" placeholder="Reply…"></textarea>
</div>
</div>
</div>
the scope is updated on enter:
$('.addComment').keypress(function(e) {
if(e.which == 10 || e.which == 13) {
$scope.currentItem.comments.push({
"user": "user3",
"message": $(this).val()
});
console.debug("currentItem", $scope.currentItem);
}
});
debugging $scope.currentItem shows that the comment has been added to it, however the view doesn't show the new comment. I suspect that the $scope is only being watched on its first level and that this is why the view doesn't update. is that the case? If so how can I fix it?
SOLUTION:
As Ajay suggested in his answer below I wrapped the array push into the apply function like this:
var el=$(this);
$scope.$apply(function () {
$scope.currentChallenge.comments.push({
"user": $scope.currentUser,
"message": el.val()
});
});
Modify the code to wrap inside scope.$apply because you are modifying the property outside the angular scope you have to use scope.$apply() to watch the values
I had to place my form inside the same div controller as the ng-repeat. I had two separate div controllers.
Use $scope.$parent.arrayObjet to modify the parent variables instead of $scope.arryaObject. It worked in my case.
<div class="col-sm-12 col-lg-12">
<div class="outer-container">
<div class="inner-container">
<div class="table-header">
<form id="teamForm" name="teamForm">
<table class="table table-bordered">
<thead>
<!-- Grid header -->
<tbody data-ng-if="(allTeamMembers.length==0)">
<tr>
<td class="text-center height_33_p" colspan="15"> {{noResultFound}} </td>
</tr>
</tbody>
<!-- Existing team member -->
<tbody data-ng-repeat="tm in teammemberDetailsArryobject|orderBy:orderByField:reverseSort" data-ng-form="innerForm_$index" data-ng-class="{'ng-submitted':innerForm_$index.$submitted}">
<tr></tr>
</tbody>
In the code I am deleting one record and add new row programmatically but all the rows are displayed in the ng-repeat rows(including deleted)

Categories