Load directives dynamically using ng-repeat - javascript

I am wrapping the HTML "select" element with my own directive. This directive should create a Dropdown menu representing it's options.
I tag the select element with my custom "arBootstrapSelect" directive/attribute.
This directive appends a Dropdown menu with the options inside it repeated by ng-repeat.
The "option" elements in the "select" element are tagged with "arBootstrapSelectOption". They should have a "content" attribute, representing a dynamic directive. This dynamic directive should be compiled and shown in the Dropdown menu.
Basiclly, each option(tagged by "arBootstrapSelectOption") compiles it's "content" attribute using the $compile service and injects it into a list living in the arBootstrapSelect directive. After that arBootstrapSelect should show the compiled options using ng-repeat. Hope it's not too complicated.
I am getting Error Link
HTML:
<select ar-bootstrap-select class="form-control">
<option ar-bootstrap-select-option value={{$index}} ng-repeat="c in countries" content="<ar-country country-id='{{$index}}'></ar-country>">
</option>
</select>
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
Dropdown
<span class="caret"></span>
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
<li ng-repeat="option in arBootstrapSelectOptions">
{{option[1]}}
</li>
</ul>
</div>
My directives:
(function () {
'use strict';
var app = angular.module('mainApp');
app.directive('arBootstrapSelect', function ($interval, $compile) {
$scope.arBootstrapSelectOptions = [];
function link(scope, element, attrs) {
//element.hide();
}
return {
restrict: 'A',
link: link,
scope: true
}
});
app.directive('arBootstrapSelectOption', function ($compile) {
function link(scope, element, attrs) {
scope.arBootstrapSelectOptions.push([attrs.value, $compile(attrs.content)(scope)]);
}
return {
scope: true,
restrict: 'A',
link: link,
}
});
})();
This works, but it's ugly and slow:
(function () {
'use strict';
var app = angular.module('mainApp');
app.directive('arBootstrapSelect', function ($interval, $compile) {
//$scope.arBootstrapSelectOptions = [];
function link(scope, element, attrs) {
//element.hide();
scope.$on('arBootstrapSelectNewItem', function (event, data) {
var test = $('<li></li>').append(data);
element.parent().find('.dropdown-menu').append(test);
});
}
return {
restrict: 'A',
link: link,
scope: true,
transclude: true
}
});
app.directive('arBootstrapSelectOption', function ($compile) {
function link(scope, element, attrs) {
//scope.arBootstrapSelectOptions.push([attrs.value, $compile(attrs.content)(scope)]);
scope.$emit('arBootstrapSelectNewItem', $compile(attrs.content)(scope));
}
return {
scope: true,
restrict: 'A',
link: link
}
});
})();

I don't fully understand your specific example, so I'll answer at a conceptual level.
It seems that at a high level all you want to is to specify a user-provided template for ng-repeat (e.g. <ar-country country-id='{{$index}}'>) and place it within a directive-provided template (e.g. within <li>).
It would be easier and more user-friendly to provide the template as content, rather than as an attribute. Then, all you'd need is to transclude the content. (I'm avoiding here the use of <option> since it is a directive on its own and I don't understand exactly what you are trying to do - I'll use <my-option> instead):
<my-option ng-repeat="c in countries">
<ar-country country-id='{{$index}}'></ar-country>
<my-option>
The directive would look like so:
.directive("myOption", function(){
return {
scope: true,
transclude: true,
template: '<li ng-transclude></li>'
}
});
This will create conceptually the following HTML:
<my-option>
<li><ar-country country-id="0"></ar-country></li>
</my-option>
<my-option>
<li><ar-country country-id="1"></ar-country></li>
</my-option>
..
(The directive arCountry will also be compiled and linked, and may generate its own content)
Additionally, if the parent needs to register each child, it's better to use require to communicate rather than $emit/$on. So, the parent needs to define a controller with a function to register children. And, again, if you need to supply an additional template, then transclude the content:
<my-select>
<my-option ng-repeat="c in countries>
<ar-country country-id='{{$index}}'></ar-country>
</my-option>
</my-select>
.directive("mySelect", function(){
return {
scope: true,
transclude: true,
template: '<h1>heading</h1><div ng-transclude></div>',
controller: function(){
// this can be called by the child
this.registerChild = function(childElement, childController){
// store the children, if needed
}
}
}
});
To make use of this.registerChild we'd need to make myOption use require:
.directive("myOption", function(){
return {
scope: true,
transclude: true,
template: '<li ng-transclude></li>'
require: ['myOption', '^mySelect'],
controller: function(){
// you can define some functions here
},
link: function(scope, element, attrs, ctrls){
var me = ctrls[0],
selectCtrl = ctrls[1];
selectCtrl.registerChild(element, me);
}
});

Related

How do I pass any array from ng-repeat to AngularJs attribute directive?

I have a list of hierarchy of menu items where each item has a child list. For The menuItems property is from the controller scope(list of parents). I want to pass an array to be consumed by the directive on both levels of the following example.
Html Code
<div sortable="menuItems">
<div ng-repeat="item in menuItems">
...
<div sortable="item.Children">
<div ng-repeat="child in menuItems.Children">...</div>
</div>
</div>
</div>
Directive code
app.directive('sortable', function ($timeout) {
return {
restrict: 'A',
link: function($scope, $elem, attrs) {
// I need access by the array in here.
}
};
});
I have set the sortable attribute to the value of the name of the list which obviously is not working for me.
You can set up a scope watch (or collection watch), since the value of the attribute is the scope expression.
app.directive('sortable', function ($timeout) {
return {
restrict: 'A',
link: function($scope, $elem, attrs) {
$scope.$watchCollection(attrs.sortable, function (newCollection, oldCollection) {
// (do something with newCollection)
});
}
};
});
The problem was the isolate-scope for the directive was not set.
app.directive('sortable', function ($timeout) {
return {
restrict: 'A',
link: function ($scope, $elem, attrs) {...},
scope: { items: '=' }
}
<div id="sortable-basic" sortable items="menuItems">

Angular | Directive not passing correct value back

Hi i have created a directive and it does not pass back the correct message.
The directive is used to pass tool-tips back to the html page
this is what the html looks like
<info-text info-msg="Adding another applicant might help you to get approved."></info-text>
below is the directive
(function(){
angular.module('mainApp').directive('infoText', [function () {
return {
scope: { infoMessage: '&infoMsg' },
restrict: 'E',
replace: true,
template: '<p class="info-text"><i class="fa fa-info-circle"></i> {{infoText}}</p>',
link: function(scope, elem, attrs) {
$(elem).prev().hover(function(){
$(elem).addClass('info-hover');
}, function(){
$(elem).removeClass('info-hover');
});
}
};
}]);
}());
the message i get rendered on the page is as follows (it does send the glyphicon):
{{infoText}}
Any ideas,
thanks. Kieran.
You should not use & for this sort of binding, basically it is used for expression binding. I think one way binding (#) is efficient for what you are doing.
Also you should change directive template {{infoText}} to {{infoMessage}}
Markup
<info-text
info-msg="{{'Adding another applicant might help you to get approved.'}}"></info-text>
Directive
angular.module('mainApp').directive('infoText', [function () {
return {
scope: { infoMessage: '#infoMsg' },
restrict: 'E',
replace: true,
template: '<p class="info-text"><i class="fa fa-info-circle"></i> {{infoMessage}}</p>',
link: function(scope, elem, attrs) {
$(elem).prev().hover(function(){
$(elem).addClass('info-hover');
}, function(){
$(elem).removeClass('info-hover');
});
}
};
}]);
And making more cleaner and readable html you could place that string into some scope variable and pass that scope variable in info-msg attribute

Dynamic NG-Controller Name

I want to dynamically specify a controller based on a config that we load. Something like this:
<div ng-controller="{{config.controllerNameString}}>
...
</div>
How do I do this in angular? I thought this would be very easy, but I can seem to find a way of doing this.
What you want to do is have another directive run before anything else is called, get the controller name from some model remove the new directive and add the ng-controller directive, then re-compile the element.
That looks like this:
global.directive('dynamicCtrl', ['$compile', '$parse',function($compile, $parse) {
return {
restrict: 'A',
terminal: true,
priority: 100000,
link: function(scope, elem) {
var name = $parse(elem.attr('dynamic-ctrl'))(scope);
elem.removeAttr('dynamic-ctrl');
elem.attr('ng-controller', name);
$compile(elem)(scope);
}
};
}]);
Then you could use it in your template, like so:
<div dynamic-ctrl="'blankCtrl'">{{tyler}}</div>
with a controller like this:
global.controller('blankCtrl',['$scope',function(tyler){
tyler.tyler = 'tyler';
tyler.tyler = 'chameleon';
}]);
There's probably a way of interpolating the value ($interpolate) of the dynamic-ctrl instead of parsing it ($parse), but I couldn't get it to work for some reason.
I'm using it in ng-repeat, so this is improved code for loops and sub objects:
Template:
<div class="col-xs6 col-sm-5 col-md-4 col-lg-3" ng-repeat="box in boxes">
<div ng-include src="'/assets/js/view/box_campaign.html'" ng-dynamic-controller="box.type"></div>
</div>
Directive:
mainApp.directive('ngDynamicController', ['$compile', '$parse',function($compile, $parse) {
return {
scope: {
name: '=ngDynamicController'
},
restrict: 'A',
terminal: true,
priority: 100000,
link: function(scope, elem, attrs) {
elem.attr('ng-controller', scope.name);
elem.removeAttr('ng-dynamic-controller');
$compile(elem)(scope);
}
};
}]);
Personally the 2 current solutions here didn't work for me, as the name of the controller would not be known when first compiling the element but later on during another digest cycle. Therefore I ended up using:
myapp.directive('dynamicController', ['$controller', function($controller) {
return {
restrict: 'A',
scope: true,
link: function(scope, elem, attrs) {
attrs.$observe('dynamicController', function(name) {
if (name) {
elem.data('$Controller', $controller(name, {
$scope: scope,
$element: elem,
$attrs: attrs
}));
}
});
}
};
}]);

AngularJS: Objects inside nested directives getting undefined?

So, I have two directives, one that has a template file, which contains another directive of the same type.
The first directive looks like:
.directive('billInfo', function () {
return {
// scope: true,
scope: {
obj: '='
},
restrict: 'E',
templateUrl: 'views/templates/bill-info.html',
link: function (scope, element, attrs) {
scope.status = scope.obj.getStatus();
scope.bill = scope.obj;
}
}
})
And the template is pretty simple, something like;
<h4>
<span class="glyphicon glyphicon-cutlery">
{{bill.getTable()}}
</span>
<small><span class="time"></span></small>
<div class="btn-group bill-btn">
<bill-btns billobj="bill"></bill-btns>
</div>
</h4>
The directive for billBtns looks like:
.directive('billBtns', function () {
return {
scope: {
billobj: '='
},
restrict: 'E',
template: '<div><div>koko{{status}}</div></div>',
link: function (scope, element, attrs) {
console.log(scope, scope.billobj);
scope.status = scope.billobj.getStatus();
}
}
})
The problem is unexpected: scope.billobj turns out to be undefined. When I console log scope from within the link function of the billBtns directive, all seems ok: I can see billobj inside scope.
What is going on here? Am I doing something fundamentally wrong here?
EDIT: Template for billInfo
<div draggable ng-repeat="(index, bill) in getEnq()" bill="bill" id="bill-{{bill.orderCode}}" class="container panel panel-default bill float-{{index%2}}" style="width:300px;" data-created="{{bill.getCreatedOn()}}">
<bill-info obj="bill"></bill-info>
</div>
I believe I've come to a solution, but I'm uncertain as to if this is the right practice. Here's what the new billBtns directive looks like:
.directive('billBtns', function () {
return {
restrict: 'E',
template: '<div><div>koko{{status}}</div></div>',
link: function (scope, element, attrs) {
console.log(scope, scope.$parent.obj);
scope.status = scope.$parent.bill.getStatus();
}
}
})
And that solves the problem. My suspicion is this, if we look at the billInfo directive again, I do something like:
scope.bill = scope.obj; // woah?
I'd like to understand more about why this happens and why I can access scope.$parent.bill from a nested directive but not scope.$parent.obj without getting typeerrors. Or maybe thats just the way to cascade scopes.

Wrapping Foundation 4 reveal in Angular

New to Angular, just trying to get some harmony with Zurb Foundation 4. A case in point; I am trying to make use of the http://foundation.zurb.com/docs/components/reveal.html component.
Straight-forward approach seemed to be to wrap as directives:
directive('modal', function() {
return {
template: '<div ng-transclude id="notice" class="reveal-modal">' +
'<a close-modal></a>' +
'</div>',
restrict: 'E',
transclude: true,
replace: true,
scope: {
'done': '#',
},
transclude: true,
link: function(SCOPE, element, attrs, ctrl) {
SCOPE.$watch('done', function (a) {
// close-modal
});
}
}
}).
directive('closeModal', function() {
return {
template: '<a ng-transclude href="#" class="close-reveal-modal">x</a>',
restrict: 'A',
transclude: true,
replace: true
}
}).
directive('showModal', function() {
return {
template: '<a ng-transclude class="reveal-link" data-reveal-id="notice" href="#"></a>',
restrict: 'A',
transclude: true,
replace: true,
}
});
This works fine up to a point, for example, I can use the modal to show different notices from a template:
<modal done="">
<div ng-include src="'partials/notices/' + notice + '.html'"></div>
</modal>
<select ng-model="notice" ng-options="n for n in ['notice-1', 'notice-2']">
<option value="">(blank)</option>
</select>
<a show-modal>show modal</a>
However, where it gets sticky is if I want to trigger close-modal/ show-modal from a controller/ on a certain event (e.g. within $watch). I'm assuming my directive needs a controller to trigger click, but would be good Angular practise?
This question is very old and I don't know if it works with Reveal. But I've wrapped the dropbox library into Angular only by calling the .foundation() method on the .run() method of angular:
app.run(function ($rootScope) {
$rootScope.$on('$viewContentLoaded', function () {
$(document).foundation();
});
});
That works for me. I guess that you can also create a directive to handle user interaction.
Controllers should not be triggering UI events directly neither manipulate UI elements directly. All that code is supposed to go in Directives.
What you can do is:
Bind a bool in Directive Scope to the Parent scope and add a watch on that. I think you already did that. OR
Do a scope.$broadcast on the controller and add scope.$watch on the directive to close then.

Categories