How To Load Template Dynamically In Angularjs
Dynamic templates in AngularJS
Sometimes y'all may find yourself that the common patterns in web development cannot support your UI requirements in terms of how dynamic a specific view can exist. Let me explain what I mean past a simple example: Presume that you have a route in your Single Page Application that displays all the azure services that a user is registered at. Each registered service has its own section on the template an of course specific functionality such as unregister, add or remove features. The question is which is the proper way to implement such a view? You lot could create a template such as the post-obit:
<div ng-controller="servicesCtrl"> <section ng-show="hasServiceOne"> <div ng-click="addFeatureToServiceOne">Service One Content</div> </department> <department ng-show="hasServiceTwo"> <div ng-click="addFeatureToServiceTwo">Service Two Content</div> </department> <department ng-testify="hasServiceThree"> <div ng-click="addFeatureToServiceThree">Service Three Content</div> </section> </div>
Indeed with this template you could display or hide specific sections depending on if the user is registered or not respectively but in that location are some drawbacks:
- The servicesCtrl controller needs to implement the functionality for all the services fifty-fifty if the user isn't registered at all of them.
- The template isn't sufficient in case we wanted to display the registered services in a specific order (dynamic behavior)
The solution: Dynamic compiled directives
The solution to the problem is to utilize custom directives for each service and add information technology to the template dynamically just if the user is registered. With this pattern you could add together each service department in any club yous desire, bold this info comes from an api. More over each directive would encapsulate its own functionality and only in the relative controller, template and css file.
Evidence me some lawmaking
I have created an SPA that solves the scenario nosotros presented before related to azure services. Each post is an opportunity to learn new things and so I found this one to also present y'all a proper fashion to create your ain AngularJS 3rd party library . Past tertiary party library i mean that you tin can encapsulate any custom angularJS elements or API yous want in a single my-library.js file and use it in any angularJS application. The source lawmaking of the application is available for download on Github. Allow'southward take a look at the compages first:
We can meet that for each service nosotros have a respective directive with all the required files forth. More specifically nosotros have directives for iv azure services, Active Directory, BizTalk, RedisCache and Scheduler. Here is the code for the RedisCache directive which is responsible to display and handle RedisCache service related functionality.
(function() { 'use strict'; angular.module('azure.redisCache', []); })(); (part() { 'use strict'; athwart .module('azure.redisCache') .directive('redisCache', redisCache); office redisCache() { //Usage: //<redis-cache></redis-cache>"/> var directive = { controller: 'RedisCache', restrict: 'E', templateUrl: 'external-lib/redisCache/redisCache.html' }; return directive; } })(); (part() { 'utilize strict'; athwart .module('azure') .controller('RedisCache', RedisCache); RedisCache.$inject = ['$scope']; office RedisCache($scope) { activate(); role activate() { } } })(); <!-- Page Content --> <div course="container rediscache"> <!-- Folio Heading/Breadcrumbs --> <div form="row"> <div class="col-lg-12"> <h1 class="page-header">{{service.championship}} <small>service</small> </h1> </div> </div> <!-- /.row --> <!-- Projects Row --> <div grade="row"> <div form="col-md-six img-portfolio"> <a href="portfolio-item.html"> <img class="img-responsive img-hover" ng-src="{{service.image01}}" alt=""> </a> <h3> <a href="portfolio-item.html">About</a> </h3> <p>Azure Redis Cache is based on the pop open-source Redis enshroud. Information technology gives you access to a secure, dedicated Redis cache, managed by Microsoft and attainable from any application inside Azure.</p> <p>Azure Redis Cache is piece of cake to use. Simply provision a cache using the Microsoft Azure portal and telephone call into its cease point using any customer that supports Redis. If you've used Redis before, you already know how to use Azure Redis Cache.</p> </div> <div class="col-md-vi img-portfolio"> <a href="portfolio-particular.html"> <img class="img-responsive img-hover" ng-src="{{service.image02}}" style="acme:207px" alt=""> </a> <h3> <a href="portfolio-item.html">High performance</a> </h3> <p>Azure Redis Cache helps your application become more than responsive even as user load increases. Information technology leverages the low-latency, loftier-throughput capabilities of the Redis engine. This separate, distributed cache layer allows your data tier to scale independently for more efficient use of compute resources in your application layer.</p> </div> </div> <!-- /.row --> </div> <!-- /.container --> .rediscache { groundwork-color: #eee; } Notice in the redisCache.html the bindings through a service object. Just where does this $scope object came from? The reply is behind the azurePanel directive which works as a container to display the azure services. Let's examine its lawmaking:
(function() { 'use strict'; angular.module('azure', [ 'azure.cadre', 'azure.activeDirectory', 'azure.bizTalk', 'azure.redisCache', 'azure.scheduler' ]); })(); The azure.cadre module holds the api that fetches whatsoever data required to feed the azure service directives. We 'll take information technology a await subsequently on.
(function() { 'use strict'; angular .module('azure') .directive('azurePanel', azPanel); office azPanel() { //Usage: //<azure-panel user='selectedUser'></azure-panel>"/> var directive = { telescopic: { 'user': '=' }, controller: 'AzurePanel', restrict: 'Due east', templateUrl: 'external-lib/azurePanel/azurePanel.html' }; render directive; } })(); This directive will take a user's id parameter in gild to fetch user's services through the api..
(role() { 'use strict'; athwart .module('azure') .controller('AzurePanel', AzurePanel); AzurePanel.$inject = ['$telescopic', 'azureapi']; office AzurePanel($scope, azureapi) { $scope.servicesLoaded = false; actuate(); function activate() { azureapi.getAzureServices($telescopic.user.id) .then(office(information) { $scope.user.services = data; $scope.servicesLoaded = true; }); } $scope.$lookout('user', function(newValue, oldValue) { actuate(); }); } })(); If the user change, we make sure to re-activate the azure directives for that user. Let'south see now how those azure directives are rendered.
<div ng-if="servicesLoaded"> <div class="row"> <div class="col-md-12" ng-repeat="service in user.services"> <azure-service service="service"> </azure-service> <hr/> </div> </div> </div>
Each service establish for the selected user is passed to an azureService directive.
(function() { 'use strict'; angular .module('azure') .directive('azureService', azureService); azureService.$inject = ['$compile']; function azureService($compile) { //Usage: //<azure-service service='service'></azure-service>"/> var directive = { scope: { 'service': '=' }, link: link, restrict: 'Due east' }; return directive; role link(telescopic, element, attrs) { var newElement = angular.element(telescopic.service.type); element.append(newElement); $compile(newElement)(telescopic); } } })(); The but thing that this directive has to do is to angularJS compile the specific directive found in the telescopic.service.type. I believe now is the correct moment to view the api..
(role() { 'employ strict'; angular .module('azure.core') .manufacturing plant('azureapi', azureapi); azureapi.$inject = ['$q', '$timeout']; function azureapi($q, $timeout) { var users = [ { id: i, services: [ { blazon: '<biz-talk></biz-talk>', title: 'BizTalk Azure', image: 'images/bizTalk.png' }, { type: '<scheduler></scheduler>', title: 'Scheduler Azure', image: 'images/azure-scheduler.png' }, { blazon: '<redis-cache></redis-cache>', title: 'Redis Cache Azure', image01: 'images/redis-cache-01.png', image02: 'images/redis-cache-02.jpg' } ] }, { id: ii, services: [ { type: '<agile-directory></active-directory>', title: 'Active Directory', image: 'images/activeDirectory.png' }, { type: '<redis-enshroud></redis-cache>', title: 'Redis Cache Azure', image01: 'images/redis-cache-01.png', image02: 'images/redis-enshroud-02.jpg' }, { blazon: '<biz-talk></biz-talk>', title: 'BizTalk Azure', image: 'images/bizTalk.png' }, ] } ]; var service = { getAzureServices: getAzureServices }; render service; function getAzureServices(userId) { var deferred = $q.defer(); var services = []; $timeout(office() { // amazing implementation services = users[userId - one].services; deferred.resolve(services); }, 1000); return deferred.promise; } } })(); As you tin come across each service has definitely a type which is being mapped to certain azure-directives. Depending on the service type yous may add any custom belongings that azure-service directive may need (dynamic behavior).
How to eat this external-lib?
The terminal production of such a library should be a JavaScript plus a css file. In social club to attain this you need to write grunt or gulp tasks that will concatenate, minify and generally optimize and package your library. I have washed this using Gulp and you tin can see those tasks here.
In the SPA app'southward side the only affair y'all demand to declare in gild to view a user'southward services is the following:
<div class="container"> <azure-panel user="selectedUser"></azure-panel> </div>
The selectedUser is just an id which will be used from the lib's api to fetch user'due south services. In the app I have declared two users's that have been registered in azure services in a different gild. You can switch the selected user and check how this library works.
That's it we accept finished! Nosotros saw how to create a re-usable angularJS library and how to create dynamic views using AngularJS. You can download the project I created from here where you lot will also find instructions on how to run information technology.
In case you find my weblog's content interesting, register your e-mail to receive notifications of new posts and follow chsakell'south Blog on its Facebook or Twitter accounts.
| .NET Spider web Application Development past Chris Due south. | |||
| | ||
Categories: Angular
How To Load Template Dynamically In Angularjs,
Source: https://chsakell.com/2016/04/13/dynamic-templates-in-angularjs/
Posted by: wrightcoma1941.blogspot.com

0 Response to "How To Load Template Dynamically In Angularjs"
Post a Comment