How should i propertly use angular templates (ng-include)? - angularjs

I made html template and want to use it with angular via ng-include.
<input class="k-textbox" ng-model="entity.Name">
i want to use it twice, so i added it into page like this
<div ng-include="'/template.html'" ng-init="entity=firstEntity"></div>
<div ng-include="'/template.html'" ng-init="entity=secondEntity"></div>
But as a result i getting 2 templates with 'secondEntity' as data, what is proper usage?

This could be a possible usage:
JS:
app.controller("myCtrl1", function($scope) {
$scope.entity = firstEntity;
}
app.controller("myCtrl2", function($scope) {
$scope.entity = secondEndity;
}
HTML:
<div ng-controller="myCtrl1">
<div ng-include="'/template.html'"></div>
</div>
<div ng-controller="myCtrl2">
<div ng-include="'/template.html'"></div>
</div>
Although, reusable templates that require passing different models or configuration are achieved using directives.
EDIT: Directive approach:
JS:
app.controller("myCtrl1", function($scope) {
$scope.entities = {entity1: {}, entity2: {}};
}
app.directive('myDirective', function() {
return {
scope: {
entity: '='
},
template: '<input class="k-textbox" ng-model="entity.Name">'
}
});
HTML:
<div ng-controller="myCtrl1">
<myDirective entity="entities.entity1"></myDirective>
<myDirective entity="entities.entity2"></myDirective>
</div>

Related

Unable to get content AngularJs dynamic popover inside ngrepeat

I need to display a small popover which should open on click and goaway on clicking anywhere on the page.
I found a plunker (http://plnkr.co/edit/K7cYQSDEBS3cHvDfJNLI?p=preview) which matches this requirement however, unable to get it to work inside ng-repeat.
I saw several answers and Plunker examples but not able to get this to work.
Here is my html
<div ng-controller="TestController">
<div class="row" style="background-color: #ebebeb !Important; ">
<div style="text-align:center">
<table style="width:100% !important;">
<tr ng-repeat="member in TeamMembers" style="font-size:18px !important; height: 108px;">
<td style="display:block;margin-top:30px;text-align:left;"> {{member.FirstName}} {{member.LastName}} <i class="fa fa-info-circle" aria-hidden="true" ng-show="member.Description != null" popover-template="dynamicPopover.templateUrl" popover-placement="bottom" popover-elem descr="{{member.Description}}"></i></td>
</tr>
</table>
</div>
</div>
...
<script type="text/ng-template" id="descriptionModal.html">
<div class="adp-info-dialog">
<div class="modal-body">
<div class="row">
<div class="col-md-8 col-md-offset-1">
<div class="form-group">
<label class="fieldset-label">Test {{ dynamicPopover.descr }}</label>
</div>
</div>
</div>
</div>
</div>
</script>
Here is the JS
testApp.controller('TestController', function ($scope, $rootScope, $log, $modal, SiebelAccountTeamService, $filter, $element) {
$scope.dynamicPopover = {
templateUrl: 'descriptionModal.html',
descr: null
};
var result = TestService.GetTeamMembers();
result.then(function (data) {
$scope.TeamMembers = data.data;
}, function (e) {
console.log(e);
}).finally(function () {
$scope.CompleteLoading();
});
});
testApp.directive('popoverClose', function ($timeout) {
return {
scope: {
excludeClass: '#'
},
link: function (scope, element, attrs) {
var trigger = document.getElementsByClassName('trigger');
function closeTrigger(i) {
$timeout(function () {
angular.element(trigger[0]).triggerHandler('click').removeClass('trigger');
});
}
element.on('click', function (event) {
var etarget = angular.element(event.target);
var tlength = trigger.length;
if (!etarget.hasClass('trigger') && !etarget.hasClass(scope.excludeClass)) {
for (var i = 0; i < tlength; i++) {
closeTrigger(i)
}
}
});
}
};
});
testApp.directive('popoverElem', function () {
return {
scope: {
descr: '#'
},
link: function (scope, element, attrs) {
$scope.dynamicPopover.descr = scope.descr,
alert($scope.dynamicPopover.descr),
element.on('click', function () {
element.addClass('trigger');
});
}
};
});
Appreciate your help.
Update:
To show the data of the ng-repeat inside the popover content, we need to access the individual objects through the $index of the ng-repeat. Refer the below example.
Plunkr Demo
The problem here is that you are using ng-repeat which creates a new scope read more here.
Since replicating the issue with your code is tedious, I tried replicating the issue with the plunkr!
Solution:
Plunkr Demo
You can simply define a new controller inside the descriptionModal.html like so
HTML:
<script type="text/ng-template" id="myPopoverTemplate.html">
<div class="adp-info-dialog" ng-controller="tester">
<div class="modal-body">
<div class="row">
<div class="col-md-8 col-md-offset-1">
<div class="form-group">
<label class="fieldset-label">Test {{ $parent.$parent.dynamicPopover.content }}</label>
</div>
</div>
</div>
</div>
</div>
</script>
JS:
app.controller('tester', function ($rootScope, $scope) {
console.log($scope.$parent.$parent.dynamicPopover.title);
});
Then, we will be able to access the parent scope, using $parent, the html inside the above script uses the $parent to get the variable!
Please note: It took me two $parent to reach the required $scope to access the scope variable. In your scenario it will also require two, the way to check how many is needed is use console.log($scope), then open the console(F12), then traverse through the objects $parent property till you find the correct $scope. Then count the number of $parent traversed, that will be your required number of $parent to traverse!
P.S:
There is another method you can do this, since this method will require a significant rewrite of your code, I will provide the GIST, you can use the controller as syntax and access the correct scope.
Here is the SO Answer giving the method to do it
SO Answer
I hope this fixes you issue.

User Input won't duplicate/display in directive template

Why are the user inputted values not duplicating when a user types into an input?
The user input works and duplicates when the HTML is separate from a custom directive template as shown below and in this fiddle: http://jsfiddle.net/Lvc0u55v/7069/ .
<div ng-controller="LeaseTemplateController">
<div class="leasespecial">
<div class="firstsec">
<div class="percNumber">
<h1 id="perId" ng-repeat="bb in percent_id">{{bb.value}}</h1>
</div>
</div>
<h2>Lease Special Template</h2>
<form>
<div class="form-group" ng-repeat="cc in percent_id">
<div class="input-group">
<input class="form-control input" type="text" placeholder="Enter Percent" ng-model="cc.value">
</div>
</div>
</form>
</div>
<script>
var myApp = angular.module('myApp', []);
myApp.controller('LeaseTemplateController', ['$scope', function($scope) {
//Lease Special Template
$scope.percent_id = [{
value: '20'
}];
}]);
</script>
However, instead I'm trying to insert it using two different directive templates as shown in this fiddle: http://jsfiddle.net/Lvc0u55v/7068/
<div lease-text-directive>
</div>
<div lease-input-directive>
</div>
<script>
var myApp = angular.module('myApp', []);
myApp.controller('LeaseTemplateController', ['$scope', function($scope) {
//Lease Special Template
$scope.percent_id = [{
value: '20'
}];
}]);
myApp.directive('leaseTextDirective', function() {
return {
restrict: 'A',
template: '<div class="leasespecial" ng-controller="LeaseTemplateController">\
<div class="firstsec">\
<div class="percNumber">\
<h1 id="perId" ng-repeat="bb in percent_id">{{bb.value}}</h1>\
</div>\
</div>'
};
});
myApp.directive('leaseInputDirective', function() {
return {
restrict: 'A',
template: '<h2>Lease Special Template</h2>\
<form ng-controller="LeaseTemplateController">\
<div class="form-group" ng-repeat="cc in percent_id">\
<div class="input-group">\
<input class="form-control input" type="text" placeholder="Enter Percent" ng-model="cc.value">\
</div>\
</div>\
</form>'
};
});
</script>
Why are the values not duplicating over in the second example and would you suggest a better practice than this?
I believe your experiencing the separation of scopes. Your directives have a different scope than your controller so it knows nothing. Try injecting your rootscope or scope like myApp.directive('leaseInputDirective', function($rootScope, $scope)
got it working now
var myApp = angular.module('myApp', []);
myApp.controller('LeaseTemplateController', function($scope,$rootScope) {
//Lease Special Template
$rootScope.percent_id = [{
value: '20'
}];
});
myApp.directive('leaseTextDirective', function() {
return {
restrict: 'E',
replace: true, // Replace with the template below
transclude: true, // we want to insert custom content inside the directive
template: '<div class="leasespecial" ng-controller="LeaseTemplateController">\
<div class="firstsec">\
<div class="percNumber">\
<h1 id="perId" ng-repeat="bb in percent_id">{{bb.value}}</h1>\
</div>\
</div>'
};
});
myApp.directive('leaseInputDirective', function() {
return {
restrict: 'E',
replace: true, // Replace with the template below
transclude: true, // we want to insert custom content inside the directive
template: '<div><h2>Lease Special Template</h2>\
<form ng-controller="LeaseTemplateController">\
<div class="form-group" ng-repeat="cc in percent_id">\
<div class="input-group">\
<input class="form-control input" type="text" placeholder="Enter Percent" ng-model="cc.value">\
</div>\
</div>\
</form></div>'
};
});
<lease-text-directive>
</lease-text-directive>
<!-- leaseTextDirective -->
<lease-input-directive>
</lease-input-directive>

Angular JS Directive loaded in expression

I'm new to Angular, and have found a ton of resources about directives and nesting, but can't seem to get this simple example to work. So basically I am working on a tabset, I have an HTML template:
tabset.html
<div>
<ul>
<li ng-repeat="tab in tabset.tabs" ng-class="{active:tabset.current()==$index}">
<a href ng-click="tabset.current($index)">{{tab}}</a>
</li>
</ul>
<div>
<div ng-repeat="pane in tabset.panes">
<div ng-show="tabset.current()==$index">
{{pane.contents}}
</div>
</div>
</div>
</div>
And a search form template:
search-form.html
<div>
<form name="ytSearch" ng-submit="YTCtrl.submit()" novalidate>
<label for="search_box">Search For: </label>
<input id="search_box" ng-model="YTCtrl.searchString"/>
<br>
<label for="location">Location: </label>
<input id="location" ng-model="YTCtrl.location"/>
within
<input type="numeric" value="100" ng-model="YTCtrl.locationRadius" />
<select ng-model="YTCtrl.locationUnit">
<option value="ft">Feet</option>
<option value="m">Meters</option>
<option value="mi">Miles</option>
<option value="km">Kilometers</option>
</select>
<br>
<label for="search_order">Sort By: </label>
<select id="search_order" ng-model="YTCtrl.order">
<option value="relevance">Relevance</option>
<option value="date">Date</option>
<option value="rating">Rating</option>
</select>
<br>
<button id="search">
Search
</button>
</form>
</div>
And a simple app file with 2 directives to handle each of the templates:
app.js
(function() {
angular.module("JHYT", [])
.directive("sidebarTabset", function($compile) {
return {
restrict : 'E',
templateUrl : 'tabset.html',
controller : function($scope, $compile, $http) {
this._current = 0;
this.current = function(i) {
if (i != null)
this._current = i;
return this._current;
};
this.tabs = ['Search', 'Favorite'];
this.panes = [{
contents : "<search-form></search-form>"
}, {
contents : "Favorite Pane"
}];
},
controllerAs : 'tabset',
};
}).
directive("searchForm", function() {
return {
restrict : 'E',
templateUrl : 'search-form.html',
controller : function($scope, $compile, $http) {
this.searchString = '';
this.location = '';
this.locationRadius = '';
this.locationUnit = 'mi';
this.order = 'relevance';
this.submit = function() {
console.log("Submit");
};
},
controllerAs : 'YTCtrl',
}
});
})();
So as you can probably tell, the idea is to be able to send a JSON object into the tabset (through a service probably) and have it build out a dynamic tabset, that actually works exactly as I expected it to. What isn't working is that in the first tab, the content, which is <search-form></search-form> is not processed, and the tag is rendered as plain text in the content area.
Since this is a tabset, the "child" doesn't need anything from the "parent", the search form and the tab itself have no scope dependencies. I tried playing with the link and compile functions after seeing some examples of nested structures, but can't seem tog et them to work.
How can I process the content of that variable so that element directives are rendered using their templates?
EDIT:
#sielakos Gave me exactly what I was hoping for, a reusable method for doing this.
I added a directive to my module called compile, which adds a wrapper to allow me to use plain text:
.directive("compile", function($compile){
return {
restrict: 'A',
link: function(scope, element, attr){
attr.$observe("compile", function(str){
var compiled = $compile("<div>"+str+"</div>")(scope);
jQuery(element).replaceWith(compiled);
})
}
}
})
And I changed my tabset to use this directive:
<div>
<ul>
<li ng-repeat="tab in tabset.tabs" ng-class="{active:tabset.current()==$index}">
<a href ng-click="tabset.current($index)">{{tab}}</a>
</li>
</ul>
<div>
<div ng-repeat="pane in tabset.panes">
<div ng-show="tabset.current()==$index">
<div compile="{{pane.contents}}"></div>
</div>
</div>
</div>
</div>
You will need to compile your string using $compile service if you wish to use it as you would use template. Otherwise it will be treated as normal string and displayed as it is.
Here is example how to use it inside directive:
var compiled = $compile(str)(scope);
element.empty();
element.append(compiled);
If you wish you can look at this fiddle for more complex example:
https://jsfiddle.net/x78uuwp2/
Here I created simple compile directive that takes string compiles it and puts as element body with current scope.

Angular JS - template of a directive ng -model does not work within ng -switch

To become more dynamic my directive decided to include the category field that makes the selection of the type of template to be displayed. As it is only a select thought of using the switch - ng instead of several html files. (google translate)
Plunker: http://plnkr.co/edit/fnCJj15XJN1kQvKq1OtZ?p=preview
index.html
<div ng-controller="MainCtrl">
<sg-combo
selected-item="selectedItem" categoria="filtro">
</sg-combo>
{{selectedItem}}
script.js
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.selectedItem = {value: null};
$scope.$watch('selectedItem',function(item){
if (item != null){
alert(item.nome); // does not display when updating
}
})
});
app.directive('sgCombo', function(){
function link(scope, elem, attrs){
scope.dados = [
{'codigo':1, 'nome':'teste1'},
{'codigo':2, 'nome':'teste2'},
{'codigo':3, 'nome':'teste3'}
];
}
return {
restrict: 'E',
scope: {
selectedItem: '=',
categoria: '#'
},
link: link,
templateUrl:"sg-combo.html"
}
})
sg-combo.html
<div ng-switch="categoria">
<div ng-switch-when="filtro" class="col-sm-4 control-label">
<div class="col-sm-4 control-label">
<label>{{label}}</label>
<select ng-model="selectedItem.value" ng-options="item.nome for item in dados" class="form-control"></select>
</div>
</div>
<div ng-switch-when="anexo" class="col-sm-4 control-label">
<div class="col-sm-4 control-label">
<label>{{label}}</label>
<select ng-model="selectedItem.value" ng-options="item.nome for item in dados" class="form-control"></select>
</div>
</div>
</div>
Try to make 'selectedItem' a part of an object.
For instance:
In controller:
$scope.options = {'selectedItem': someItem};
In template:
ng-model="options.selectedItem"
ng-switch adds a scope and you should use '.' in ng-model.

ANgularjs: ng-repeat and nested custom directive

I am trying to ng-repeat a custom directive, which has an attribute that should change over the iteration.
This is my html:
<div ng-controller="WalletsController as controller">
<bitcoin-address ng-repeat="bitcoin_label in controller.getWallets()" bitcoin-label="bitcoin_label"></bitcoin-address>
</div>
This is my controller:
(function() {
var app = angular.module('wallets', [ ]);
app.controller(
"WalletsController",
function($scope, $http) {
this.wallets = [];
var controller = this;
this.getWallets = function() {
return controller.wallets;
};
$http.get("wallet_addresses").success(
function(data) {
for (var i = 0; i < data.length; i++) {
var curWallet = data[i];
$scope[curWallet.label] = {
label: curWallet.label,
address: curWallet.address,
balance: curWallet.balance
};
controller.wallets.push(curWallet.label);
}
}
);
});
app.directive(
'bitcoinAddress',
function() {
return {
restrict: 'E',
templateUrl: '../../resources/html/bitcoin-address.html',
scope: {
bitcoinLabel: '=',
}
};
}
);
})();
And this is my template:
<div class="col-md-8 dashboardAddressCell dropdown-toggle" data-toggle="dropdown">{{bitcoinLabel.address}}</div>
What happens is that the template can not resolve the bitcoinLabel variable. I have tried specifying a constant value and the template works. My conclusion is that I am not correctly specifying the bitcoin_label attribute in the html section.I have also tried using {{bitcoin_address}}, but angularjs complains about that.
I have also tried with the following html code:
<div ng-controller="WalletsController as controller">
<!-- <tr><th>Indirizzo</th><th>Saldo</th><th></th>-->
<div ng-repeat="bitcoin_label in controller.getWallets()">
{{bitcoin_label}}
<bitcoin-address bitcoin-label="bitcoin_label"></bitcoin-address>
</div>
<bitcoin-address bitcoin-label="ciccio"></bitcoin-address>
</div>
It does not work either, but at least it shows the {{bitcoin_label}} value.
The problem seems pretty simple. Instead of
controller.wallets.push(curWallet.label);
you should push corresponding $scope[curWallet.label] object:
controller.wallets.push($scope[curWallet.label]);
Because curWallet.label is just a string so in the first case wallets ends up as array of stings. However you need wallets to be an array of objects, each having address, label, balance properties.
You have some problems with your logic. You're putting wallet labels into .wallets, then iterating over the labels, and then in your bitcoinAddress template you're trying to read .address property of the label string (not from the object where you saved it). Why not simplify the whole thing to this script:
.controller("WalletsController", function($scope, $http) {
$scope.wallets = [];
$http.get("wallet_addresses").success(function(data) {
$scope.wallets = data.slice();
});
})
.directive('bitcoinAddress', function() {
return {
restrict: 'E',
templateUrl: '...',
scope: {
wallet: '=',
}
};
})
this directive template:
<div class="..." ...>{{wallet.address}}</div>
and this body template:
<div ng-controller="WalletsController as controller">
<bitcoin-address ng-repeat="wallet in wallets" wallet="wallet"></bitcoin-address>
</div>
Both bitcoinAddress and ng-repeat directives creating scopes on the same element could cause some conflict (isolate scope in the bitcoinAddress case).
Try adjusting your html structure slightly:
<div ng-controller="WalletsController as controller">
<div ng-repeat="bitcoin_label in controller.getWallets()">
<bitcoin-address bitcoin-label="bitcoin_label"></bitcoin-address>
</div>
</div>
Why not use $scope.wallets instead of this.wallets? Also in your getWallets function. After that try
<div ng-controller="WalletsController">
<div ng-repeat="bitcoin_label in wallets">
<bitcoin-address bitcoin-label="bitcoin_label"></bitcoin-address>
</div>
</div>
But if your wallets is an array of non-object like array of string or integer, use
<div ng-controller="WalletsController">
<div ng-repeat="bitcoin_label in wallets track by $index">
<bitcoin-address bitcoin-label="wallets[$index]"></bitcoin-address>
</div>
</div>

Resources