I'm using Bootstrap and AngularJS to dynamically create clickable tabs in HTML. More specifically, I'm using the ng-switch and ng-switch-when directives to control which tab's content is displayed at any given time.
PLEASE NOTE: Below you'll notice I use a controller for DOM manipulation. I realize the "AngularJS way" to perform DOM manipulation is with directives (and not controllers). I'm not one to deliberately violate good coding practices, but since I'm trying to understand this exact issue I've stumbled across while learning about controllers and directives, I'm asking you to only consider using a controller for now since that's what I believe may be contributing to the issue.
If you keep reading you'll notice I've already found a directive-based solution (i.e., the "AngularJS way"), but I'm specifically asking about the issue that occurs when using a controller and ng-switch-when.
The Problem:
The issue I'm facing is as follows. When I append div tags (containing a ng-switch-when directive) onto a container, and then compile these tags using $compile, somehow the content of each tag using ng-switch-when becomes duplicated. To keep this question from becoming too long, I've placed the idea behind what the code's expected behavior is in the comments of the first JSFiddle below, which demonstrates the issue.
JSFiddle: What I have now -- Uses controller for DOM manipulation ("non-AngularJS way"), results in unexpected duplication of tags using ng-switch-when.
An in-depth description of how to reproduce the duplication is as follows. Upon creating a new tab, it appears that the previously clicked tab's content (within the div containing ng-switch-when) is duplicated. You can see this happen by loading the above JSFiddle, right-clicking the Default text, selecting Inspect element, and then pressing Analysis > Create Tab in the tabbed pane. You'll see there are now two div tags with ng-switch-when="Default" instead of just one. If you continue to create new tabs, this pattern continues for view1, view2, and so on. Alternatively, just click Analysis > Create Tab 5 times and then look at the duplicates in Tabs 1-4. Either way, you'll see the previously selected tab's contents are doubled whenever a new tab is created.
Frustrated by this unexpected behavior, I went ahead and implemented a directive-based solution using AngularUI's Bootstrap components, which creates custom directives for tab components, to gain the desired functionality.
JSFiddle: What I want to happen in the above JSFiddle -- Uses directives for DOM manipulation ("AngularJS way").
However, as I've mentioned, I want to know why my first JSFiddle is not working. See below for formal question.
Points to consider:
The issue may be related to scope, the order the scripts are loaded, or possibly a logic error.
Perhaps it's something AngularJS simply cannot do. I'm aware that compound transclusion no longer works as of v1.2, and this issue may be related.
So my question is as follows:
Why is this duplication occurring? Is there a way to prevent/workaround the duplicates from being created? Remember, I wouldn't use this in practice, I'm just curious if this issue can be solved at all.
PLEASE NOTE: I am not looking to resolve this using jQuery, such as this jQuery solution. Although I'm aware AngularJS uses a lighter version of jQuery called jqLite under the hood, I'm looking for a "pure AngularJS" solution.
HTML:
<!-- Include CDNs (see JSFiddle above) -->
<!-- Wrap in HTML tags, include DOCTYPE -->
<body ng-app="myApp">
<div class="panel panel-default" ng-controller="myCtrl">
<div class="panel-heading">
<ul class="nav nav-tabs">
<li class="active">
<a class="h4">My App</a>
</li>
<li class="dropdown">
<a href="" class="dropdown-toggle h4" data-toggle="dropdown">
Analysis
<span class="caret"></span>
</a>
<ul class="dropdown-menu">
<li>
<button id="createTabLink" class="h4" ng-click="createTabClick()">Create Tab</button>
</li>
</ul>
</li>
</ul>
</div>
<div class="panel-body">
<div class="panel panel-default">
<div class="panel-heading">
<ul id="createTabDiv" class="nav nav-tabs"></ul>
</div>
<div class="panel-body">
<div id="viewWrapper" ng-switch="" on="viewSelected">
<div id="Default" ng-switch-when="Default">Default</div>
</div>
</div>
</div>
</div>
</div>
</body>
JS:
angular.module('myApp', []);
function myCtrl($scope, $compile) {
$scope.count = 0;
$scope.viewSelected = "Default";
$scope.tabClick = function($event) {
var tab = $event.target;
var viewName = tab.getAttribute("value");
$scope.viewSelected = viewName;
};
$scope.createTabClick = function() {
$scope.count++;
var viewName = "view" + $scope.count;
var createTabDiv = angular.element(document.querySelector('#createTabDiv'));
var viewWrapper = angular.element(document.querySelector('#viewWrapper'));
var $comp1 = createTabDiv.append('<li class="active"><a class="h4" value="' + viewName + '" ng-click="tabClick($event)">Tab ' + $scope.count + '</a></li>');
$compile($comp1)($scope);
var $comp2 = viewWrapper.append('<div id="' + viewName + '" ng-switch-when="' + viewName + '">' + viewName + '</div>');
$compile($comp2)($scope);
$scope.viewSelected = viewName;
};
}
Related
I am making a menu with AngularJs and I want that, clicking on the item, the page will scroll to the section of the clicked item.
My code is the following:
script.js
var app = angular.module('allApps',['ui.bootstrap']);
app.controller("menuCtrl",function($scope, $location, $anchorScroll){
$scope.menuItems=[
{page:"Biography", id:"bio"},
{page:"Curriculum Vitae", id:"cv"},
{page:"Gallery", id:"gallery"},
{page:"Video", id:"video"},
{page:"Press", id:"press"},
{page:"News", id:"news"},
{page:"Contact", id:"contact"}
];
$scope.scrollTo = function(id) {
$location.hash(id);
console.log($location.hash());
$anchorScroll();
};
});
menu.html
<ul class="nav nav-pills" id="mainMenu" ng-controller="menuCtrl">
<li class="active">Home</li>
<li ng-repeat="item in menuItems"><a ng-click="scrollTo('{{item.id}}')" href="">{{item.page}}</a>
</ul>
the code like this doesn't work but, if I write explicitly
ng-click="scrollTo('bio')"
it does (obviously it will scroll all the links to biography page).
I thought it was a problem in reading AngularJs directions but if I check it with firebug I can see it takes the correct id's.
May you tell me what is wrong?
You had incorrect expression in ng-click directive, basically it should not contain {{}} interpolation directive in it. The expression which you provide to ng-click will directly evaluate with the context of controller
ng-click="scrollTo(item.id)"
I am studying AngularJS by looking at the website http://campus.codeschool.com/courses/shaping-up-with-angular-js/contents and downloaded the videos, then going through the examples on my computer.
Everything went well until the video codeschool_1329.mp4, otherwise called "Shaping_Up_With_Angular_JS_Level_2b". The example works correctly when the logic for selecting the panels is in the HTML code, but when the logic is moved to a controller, it no longer works correctly. Thus I have the relevant HTML code:
<section ng-controller="PanelController as panel">
<ul class="nav nav-pills">
<li ng-class="{active:panel.isSelected(1)}">
<a href ng-click="panel.selectTab(1)">Description</a>
</li>
<!-- Repeated for Specifications and Reviews -->
</ul>
</section>
<div class="panel" ng-show="panel.isSelected(1)">
<h4>Description</h4>
<p>{{product.description}}</p>
</div>
<!-- Repeated for Specifications and Reviews -->
and for the JavaScript code I have:
app.controller('PanelController', function(){
this.tab = 1;
this.selectTab = function(setTab){
this.tab = setTab;
};
this.isSelected = function(checkTab){
return this.tab === checkTab;
};
});
exactly as in the video. The latter is with the Angular module and another Angular controller for the store.
With both Google Chrome and Firefox, when I click on the each of the tabs "Description", "Specifications" and "Reviews", the selected tab is highlighted, as in the video, albeit blue rather than dark purple, but the text that is supposed to be displayed below the selected tab does not show up at all. It looks as if there is some type of a problem with the isSelected function in PanelController with ng-show="panel.isSelected(1)", etc. in the lower part of the HTML code, although it appears to work correctly with ng-class="{active:panel.isSelected(1)}" when the tab is highlighted.
This works correctly when the logic for this is in the HTML code, as I said above, but no matter what I can do, I am unable to get this to work correctly when the logic is in PanelController.
There must be something simple that I am missing, and would be grateful to get this sorted out - many thanks.
<section ng-controller="PanelController as panel">
...
</section>
<div class="panel" ng-show="panel.isSelected(1)">
Only the section element is controlled by the panel controller, but you're trying to use panel.isSelected(1) out of that section. So that can't work.
Put the div inside the section, or wrap everything with another div and move ng-controller="PanelController as panel"to that wrapping div.
I'm trying to do a very simple thing. I'm displaying a list of values with Edit links beside them. Clicking the edit link reveals a form that lets you update the value.
(I've simplified the question so the items just have one field "name". My actual use case has more fields, but is canonically equivalent.)
I've run into something that looks like a bug in Angular, but given my limited experience with it, I'm not so sure. Here's how I'm trying to do it:
<div ng-repeat-start="item in items" ng-controller="ItemCtrl as ctrl" ng-hide="ctrl.isEditing">
<span>Name: {{item.name}}.</span>
<a href='#' ng-click='ctrl.startEditing()'>Edit</a>
</div>
<div ng-repeat-end ng-show="ctrl.isEditing">
<input type='text' ng-model='item.name'/>
<a href='#' ng-click='ctrl.save()'>Save</a>
</div>
My controller looks like this:
app.controller('ItemController', function() {
this.isEditing = false;
this.startEditing = function() { this.isEditing = true; }
this.save = function() { this.isEditing = false; }
});
Clicking on Edit link calls the right controller function, and the first div hides. But the second div does not hide.
When I rearrange the code to look like this (essentially wrapping the two divs with a wrapper element), all is well.
<div ng-repeat="item in items" ng-controller="ItemCtrl as ctrl">
<div ng-hide="ctrl.isEditing">
<span>Name: {{item.name}}.</span>
<a href='#' ng-click='ctrl.startEditing()'>Edit</a>
</div>
<div ng-show="ctrl.isEditing">
<input type='text' ng-model='item.name'/>
<a href='#' ng-click='ctrl.save()'>Save</a>
</div>
</div>
Any idea what is technically wrong with the first version? Note that the <input> boxes do get populated with the right values from item.name.
PS: There's a reason why I'm trying to keep the two divs siblings: in my use case, they are actually implemented as two trs which are supposed to appear right below each other in a table.
It's not a bug from angular but it is quite logical.
<div ng-repeat-start="item in items" ng-controller="ItemCtrl as ctrl" ng-hide="ctrl.isEditing">
<span>Name: {{item.name}}.</span>
<a href='#' ng-click='ctrl.startEditing()'>Edit</a>
</div>
<div ng-repeat-end ng-show="ctrl.isEditing">
<input type='text' ng-model='item.name'/>
<a href='#' ng-click='ctrl.save()'>Save</a>
</div>
If you see the above code you have injected controller only to the first div so obviously sibling div doesn't know what is ctrl or ItemCtrl until and unless you do as in you second way.
So if you want to achieve it as sibling, if you are using routing then add the controller attribute in your route path.
So that the controller will be active for that entire template and you can achieve what you want.
Hope it helps.
Thats because controller has its own scope. When you placed controller ONLY on your first div controllers' scope is limited to only this one div. When you wrapped both your divs inside another and place controller on wrapper, controllers' scope now is all that inside this wrapper. So in this case this works fine and this is not the angular bug
Hi all you experts out there.
My testing area: http://plnkr.co/edit/ddJT1e4a8L5NTSIVNTk7
I am trying to visualize hierarchical data in a tree-form with Angular, even though i'm using some samples to aid me in my quest (like http://jsfiddle.net/alalonde/NZum5/ and http://jsfiddle.net/brendanowen/uXbn6/8/) i fail.
As soon as i place the recursive element ng-include inside the ng-repeat in side the template it self, the memory usage of its browser-window goes through the roof and effectively hangs the browser. But the available tree-sample i could find are doing just that.
What am i missing?
You need to use the same variable name in the template. The current node is called node in the controller then child in the template.
This cause the template to render the same node over again.
It works fine if you use the same variable name :
<li ng-repeat="node in node.children" ng-include="'node.html'"></li>
See it in action here : http://plnkr.co/edit/mjfdSEDcMK8kGCRjS6V6?p=preview
If anyone here wants to avoid having the extra ng-repeat outside of the template (where it kind of includes stuff from the template anyway), here's a fiddle showing how to do it:
http://jsbin.com/hokupe/1/edit
Also here's a blog post and a 10-15 minutes video on how it works:
http://gurustop.net/blog/2014/07/15/angularjs-using-templates-ng-include-create-infinite-tree/
Sample Code:
<script type="text/ng-template" id="treeLevel.html">
<ul>
<li ng-repeat="item in items">
<input type="checkbox"
name="itemSelection"
ng-model="item._Selected" />
{{item.text}}
<div ng-include=" 'treeLevel.html'"
onload="items = item.children">
</div>
</li>
</ul>
</script>
<div ng-include=" 'treeLevel.html' "
onload="items = sourceItems">
</div>
this is my basic scenario. For a list of items (summary view) i want to show details view of item that got clicked on the same page.
I took this jsfiddle example and transformed it into this jsfiddle. If you look at the behavior it does work for first time but it is not consistent.
Maybe someone can help me with this, or suggest a better approach. I would like to have a different controller for managing the list and a different controller to handle the detail view.
One way of transforming the example (provided that you want to use ngSwitch) would be:
<ul ng-controller="ListController">
<li ng-repeat="item in items" ng-controller="ItemController">
<div ng-click="open(item)">{{item.content}}</div>
</li>
<hr>
<ng-switch on="anyItemOpen()">
<div ng-switch-when="true">
<div ng-controller="ItemController">
{{opened.name}}: overlay: tweet, share, pin
</div>
<a ng-click="close()">close</a>
</div>
</ng-switch>
</ul>
And here is the working jsFiddle: http://jsfiddle.net/pkozlowski_opensource/sJdzt/4/
Your jsFiddle didn't work since you were trying to reference item created in the ngRepeat scope (and thus not available outside of the ngRepeat).