Angular - linking to a ngInclude partial - javascript

I have followed the documentation on setting up ngInclude and have it working (loading in HTML partials) and changing the partial when a select option is changed.
$scope.templates = [
{ name: 'Overview', url: 'partials/project/overview.html' },
{ name: 'Tasks', url: 'partials/project/tasks.html' }
];
$scope.template = $scope.templates[0];
----
<div ng-controller="Tasks">
<select ng-model="template" ng-options="t.name for t in templates">
<option value="">(blank)</option>
</select>
<section ng-include="template.url"></section>
</div>
However, I don't want to use a select menu to navigate. I want to use an unordered list. I tried using ngHref, but that doesn't seem to work. I can't find much documentation on binding an element to change an ngInclude partial, but maybe I'm searching for the wrong thing.
Any help on how I could use anchor tags to change the partial being loaded in on click would be great.
Here's the structure I was playing around with:
<ul class="header-menu">
<li><a ng-modal="template" ng-href="{{template[0]}}" class="selected">Overview</a></li>
<li><a ng-modal="template" ng-href="{{template[1]}}">Tasks</a></li>
</ul>

You just need to store the path to your template, and change it based on an action in your list. ngHref isn't related here, because it would load the template itself which isn't what you want.
See this demo plunker:
HTML:
<body ng-controller="MainCtrl">
<ul>
<li ng-repeat="template in templates">
{{template.name}}
<button ng-click="selectTemplate(template)">Go!</button>
</li>
</ul>
{{selectedTemplate}}
<div ng-include="selectedTemplate"></div>
</body>
Controller:
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.templates=[{
name:'First Template',
url:'template1.html'
}
,{
name:'Second Template',
url:'template2.html'
}
]
$scope.selectedTemplate=$scope.templates[0].url;
$scope.selectTemplate=function(template){
$scope.selectedTemplate=template.url;
}
});
But I really suggest you to check out to check out ui-router, as it sounds like you are trying to implement some tab system, and changing states for your app, and ui-router does that perfectly.

Related

How to show another text value insteadof showing of existing from ng-repeat for one property using angularjs?

I have data:
html:
<div ng-controller="MainCtrl">
<ul>
<li ng-repeat="item in demo">
{{item.text}}
</li>
</ul>
</div>
js:
angular.module('MyApp', [])
.controller('MainCtrl', [function ($scope) {
$scope.demo=[
{"id":"ABC", "name":"ABC","text":"ABC"},
{"id":"PQR","name":"PQR","text":"PQR"},
{"id":"XYZ","name":"XYZ","text":"XYZ"}
];
}]);
I want to display the output like below on html view page:
ABC
PQR
MNO
instead of showing:
ABC
PQR
XYZ
i.e ex: I want to show the text value as: "MNO" instead of "XYZ" on displaying of view page, I don't want to change anything in the variable($scope.demoValues) using angularjs. I am not sure how to develop this. Please help me. Thanks.
Created Fiddle.
If you're simply looking to do a straight text replacement in the view when a particular value is encountered, you could use string.replace as follows:
<li ng-repeat="item in demo">
{{ item.text.replace('XYZ', 'MNO') }}
</li>

How do I generate a standalone HTML page in Angular

I want to generate a full standalone HTML page.
So far I've tried:
$compile(
angular.element('
<html>
<body>
<div>{{stuff}}</div>
<ul>
<li data-ng-repeat="item in list">
{{item}}
</li>
</ul>
</body>
</html>
')
)({
stuff: 'Things',
list: [
'item1',
'item2'
]
});
But that only returns a text element.
I've successfully used $interpolate for the variables alone, but that won't work for the ng-repeat and other directives.
How would I generate a fully compiled HTML page on the frontend?
If your question is "why would you do this?", think of a page creator interface, where the user might input some of the variables and expect an HTML page in response.
I'm not sure I completely understand your question, but I've created the snippet below. Is this what you want to achieve? An important thing I changed about your example, is that I created the scope for the link function by using $rootScope.$new(). It doesn't work by using simply a plain javascript object.
angular.module('test', [])
.controller('test', function($rootScope, $rootElement, $compile) {
var element = angular.element('<html><body><div>{{stuff}}</div><ul><li ng-repeat="item in list">{{item}}</li></ul></body></html>');
var scope = $rootScope.$new();
scope.stuff = 'Things';
scope.list = [
'item1',
'item2'
];
var result = $compile(element)(scope);
$rootElement.append(result);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="test" ng-controller="test"></div>

How to setup ngclass change when route change occurs in AngularJS?

I am trying to add a class on my main .container class when the route changes.
My current simple solution involves an ng-click on every main menu url (no other urls on the page):
app.controller('MainCtrl', ['$scope', function( $scope ){
$scope.setMain = function( value ){ $scope.isMain = value };
}]);
Then in my html:
<div ng-controller="MainCtrl" class="container" ng-class="{'main': isMain}">
<ul class="main-menu">
<li><a href="#" ng-click="setMain(true)"></li>
<li><a href="#/page-1" ng-click="setMain(false)"></li>
<li><a href="#/page-2" ng-click="setMain(false)"></li>
</ul>
<div ng-view></div>
</div>
This seems to work ok as long as I need to add any more urls the problem is when a user does not click on any of the links and directly accesses a url he does not get the main class.
Is there a better way to do this?
You could use a few different options, but I think the easiest for you would be to setup the $scope.isMain value on controller initialisation by looking at $location. So inside the controller you could have something like:
var loc = $location.path();
if(loc === /* some route rule you require */){
$scope.isMain = true;
}
Have a look here: http://docs.angularjs.org/api/ngRoute/service/$route as the example down the bottom has a few different examples of what sort of data you can access with regards to the route.

Complex nesting of partials and templates

My question involves how to go about dealing with complex nesting of templates (also called partials) in an AngularJS application.
The best way to describe my situation is with an image I created:
As you can see this has the potential to be a fairly complex application with lots of nested models.
The application is single-page, so it loads an index.html that contains a div element in the DOM with the ng-view attribute.
For circle 1, You see that there is a Primary navigation that loads the appropriate templates into the ng-view. I'm doing this by passing $routeParams to the main app module. Here is an example of what's in my app:
angular.module('myApp', []).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when("/job/:jobId/zones/:zoneId", { controller: JobDetailController, templateUrl: 'assets/job_list_app/templates/zone_edit.html' }).
when("/job/:jobId/initial_inspection", { controller: JobDetailController, templateUrl: 'assets/job_list_app/templates/initial_inspection.html' }).
when("/job/:jobId/zones/:zoneId/rooms/:roomId", { controller: JobDetailController, templateUrl: 'assets/job_list_app/templates/room_edit.html' })
}]);
In circle 2, the template that is loaded into the ng-view has an additional sub-navigation. This sub-nav then needs to load templates into the area below it - but since ng-view is already being used, I'm not sure how to go about doing this.
I know that I can include additional templates within the 1st template, but these templates are all going to be pretty complex. I would like to keep all the templates separate in order to make the application easier to update and not have a dependency on the parent template having to be loaded in order to access its children.
In circle 3, you can see things get even more complex. There is the potential that the sub-navigation templates will have a 2nd sub-navigation that will need to load its own templates as well into the area in circle 4
How does one go about structuring an AngularJS app to deal with such complex nesting of templates while keeping them all separate from one another?
UPDATE: Check out AngularUI's new project to address this problem
For subsections it's as easy as leveraging strings in ng-include:
<ul id="subNav">
<li><a ng-click="subPage='section1/subpage1.htm'">Sub Page 1</a></li>
<li><a ng-click="subPage='section1/subpage2.htm'">Sub Page 2</a></li>
<li><a ng-click="subPage='section1/subpage3.htm'">Sub Page 3</a></li>
</ul>
<ng-include src="subPage"></ng-include>
Or you can create an object in case you have links to sub pages all over the place:
$scope.pages = { page1: 'section1/subpage1.htm', ... };
<ul id="subNav">
<li><a ng-click="subPage='page1'">Sub Page 1</a></li>
<li><a ng-click="subPage='page2'">Sub Page 2</a></li>
<li><a ng-click="subPage='page3'">Sub Page 3</a></li>
</ul>
<ng-include src="pages[subPage]"></ng-include>
Or you can even use $routeParams
$routeProvider.when('/home', ...);
$routeProvider.when('/home/:tab', ...);
$scope.params = $routeParams;
<ul id="subNav">
<li>Sub Page 1</li>
<li>Sub Page 2</li>
<li>Sub Page 3</li>
</ul>
<ng-include src=" '/home/' + tab + '.html' "></ng-include>
You can also put an ng-controller at the top-most level of each partial
Well, since you can currently only have one ngView directive... I use nested directive controls. This allows you to set up templating and inherit (or isolate) scopes among them. Outside of that I use ng-switch or even just ng-show to choose which controls I'm displaying based on what's coming in from $routeParams.
EDIT Here's some example pseudo-code to give you an idea of what I'm talking about. With a nested sub navigation.
Here's the main app page
<!-- primary nav -->
Page 1
Page 2
Page 3
<!-- display the view -->
<div ng-view>
</div>
Directive for the sub navigation
app.directive('mySubNav', function(){
return {
restrict: 'E',
scope: {
current: '=current'
},
templateUrl: 'mySubNav.html',
controller: function($scope) {
}
};
});
template for the sub navigation
Sub Item 1
Sub Item 2
Sub Item 3
template for a main page (from primary nav)
<my-sub-nav current="sub"></my-sub-nav>
<ng-switch on="sub">
<div ng-switch-when="1">
<my-sub-area1></my-sub-area>
</div>
<div ng-switch-when="2">
<my-sub-area2></my-sub-area>
</div>
<div ng-switch-when="3">
<my-sub-area3></my-sub-area>
</div>
</ng-switch>
Controller for a main page. (from the primary nav)
app.controller('page1Ctrl', function($scope, $routeParams) {
$scope.sub = $routeParams.sub;
});
Directive for a Sub Area
app.directive('mySubArea1', function(){
return {
restrict: 'E',
templateUrl: 'mySubArea1.html',
controller: function($scope) {
//controller for your sub area.
}
};
});
You may checkout this library for the same purpose also:
http://angular-route-segment.com
It looks like what you are looking for, and it is much simpler to use than ui-router. From the demo site:
JS:
$routeSegmentProvider.
when('/section1', 's1.home').
when('/section1/:id', 's1.itemInfo.overview').
when('/section2', 's2').
segment('s1', {
templateUrl: 'templates/section1.html',
controller: MainCtrl}).
within().
segment('home', {
templateUrl: 'templates/section1/home.html'}).
segment('itemInfo', {
templateUrl: 'templates/section1/item.html',
controller: Section1ItemCtrl,
dependencies: ['id']}).
within().
segment('overview', {
templateUrl: 'templates/section1/item/overview.html'}).
Top-level HTML:
<ul>
<li ng-class="{active: $routeSegment.startsWith('s1')}">
Section 1
</li>
<li ng-class="{active: $routeSegment.startsWith('s2')}">
Section 2
</li>
</ul>
<div id="contents" app-view-segment="0"></div>
Nested HTML:
<h4>Section 1</h4>
Section 1 contents.
<div app-view-segment="1"></div>
I too was struggling with nested views in Angular.
Once I got a hold of ui-router I knew I was never going back to angular default routing functionality.
Here is an example application that uses multiple levels of views nesting
app.config(function ($stateProvider, $urlRouterProvider,$httpProvider) {
// navigate to view1 view by default
$urlRouterProvider.otherwise("/view1");
$stateProvider
.state('view1', {
url: '/view1',
templateUrl: 'partials/view1.html',
controller: 'view1.MainController'
})
.state('view1.nestedViews', {
url: '/view1',
views: {
'childView1': { templateUrl: 'partials/view1.childView1.html' , controller: 'childView1Ctrl'},
'childView2': { templateUrl: 'partials/view1.childView2.html', controller: 'childView2Ctrl' },
'childView3': { templateUrl: 'partials/view1.childView3.html', controller: 'childView3Ctrl' }
}
})
.state('view2', {
url: '/view2',
})
.state('view3', {
url: '/view3',
})
.state('view4', {
url: '/view4',
});
});
As it can be seen there are 4 main views (view1,view2,view3,view4) and view1 has 3 child views.
You may use ng-include to avoid using nested ng-views.
http://docs.angularjs.org/api/ng/directive/ngInclude
http://plnkr.co/edit/ngdoc:example-example39#snapshot?p=preview
My index page I use ng-view. Then on my sub pages which I need to have nested frames. I use ng-include.
The demo shows a dropdown. I replaced mine with a link ng-click.
In the function I would put $scope.template = $scope.templates[0]; or $scope.template = $scope.templates[1];
$scope.clickToSomePage= function(){
$scope.template = $scope.templates[0];
};
Angular ui-router supports nested views. I haven't used it yet but looks very promising.
http://angular-ui.github.io/ui-router/

AngularJS + jQuery Mobile w/ No Adapter & Disabled Routing - Used For UI Styling Only

I am learning AngularJS and have built a small application. Now that it's functionally complete, I'd like to style it up using jQuery Mobile.
Originally I dropped in tigbro's jquery-mobile-angular-adapter, but ultimately decided it was more complicated and involved than I needed. I'm not after any fancy screen transitions or page management features in jQuery Mobile - I just want to use it for styling the application and let AngularJS handle the rest.
I read this post, which has the same goal in mind, albeit with another framework, and contains a code snippet to disable the jQuery Mobile routing.
I've applied that snippet to my application in this order of script loading, just before the close body tag:
jQuery
snippet
jQuery Mobile
AngularJS
This snippet placement is the only one that works, or somewhat works anyway, in that anything in my index loads styled properly (header and main nav, basically), and my AngularJS routes work just fine, but any dynamically loaded templates that populate my ng-view, despite having jQuery Mobile data-roles (ul as listview, etc.), are not styled by jQuery Mobile; they're just plain HTML.
Does anyone have an idea as to how I could get those dynamically loaded templates to also be styled?
My index HTML structure looks like this:
<body>
<div data-role="page">
<div data-role="header" data-position="fixed">
<h1>MyApp</h1>
Home
Add
</div>
<div data-role="content" ng-view></div>
</div>
<!-- Scripts -->
</body>
And here's an example of one of my templates:
<ul data-role="listview" ng-controller="MyListCtrl">
<li ng:repeat="item in things">
{{ item.title }}<br/>{{ formatDateForDisplay(item.addDate) }}
</li>
</ul>
Thank you!
I ended up putting together this directive:
angular.module('myApp.directives', []).
directive('applyJqMobile', function() {
return function($scope, el) {
setTimeout(function(){$scope.$on('$viewContentLoaded', el.trigger("create"))},1);
}
});
Then inside of each template, wrap the template content in a div and apply the directive there, i.e.:
<div ng-controller="MyController" apply-jq-mobile>
<!-- Template Content to be jQ Mobilezed -->
</div>
This works, but because of the setTimeout, the content flashes for a split second when loading. I'm still working on figuring how how to get rid of the flash.
To note, without the setTimeout in place, the data-role="listview" wouldn't be styled (I'm guessing since it had to be populated by ng-repeat still), but any static content in the view was styled.
For some reason, el.trigger("create") doesn't work for me. After looking at the angularjs-jqm-adapter, I found it uses el.parent().trigger("create"), which it works for me.
I'm pretty much working on the same thing (no jqm angular adapter). Here's my directive that gets triggered after the last element of the repeat:
Application.Directives.directive('jqmCollapsibleRepeat', function () {
return function (scope, element, attrs) {
if (scope.$last) {
$(element).parent().trigger("create");
}
};
});
and here's part of my view that uses it:
<div data-role="collapsible" data-collapsed="true" data-transition="slide" ng-repeat="document in documents" jqm-collapsible-repeat>
<h3>{{document.FileName}}</h3>
...
</div>
For me this worked:
html:
<ul data-role="listview" data-filter="true" data-filter-placeholder="Suchen" data-inset="true">
<li ng-repeat="alert in alerts" li-jq-mobile>
{{name}}
</li>
</ul>
js:
angular.module('alertList', [])
.directive('liJqMobile', function() {
return function($scope, el) {
$scope.$on('$viewContentLoaded', el.parent().listview('refresh'));
});
for jqm pages and lists for me worked:
For pages:
<div applyjqmobile data-role="page" >
and for the list:
<li lijqmobile ng-repeat="aviso in avisos" data-icon="false" >
And directives:
.directive('applyJqMobile', function() {
return function($scope, el) {
console.log('applyJqMobile');
$(el).hide();
setTimeout(function(){$scope.$on('$viewContentLoaded', el.parent().trigger("create"))},1);
$(el).show();
}
}).directive('liJqMobile', function() {
return function($scope, el) {
console.log('liJqMobile');
$(el).hide();
setTimeout(function(){ $scope.$on('$viewContentLoaded', el.parent().listview('refresh'))},1);
$(el).show();
}
})

Categories

Resources