Simultaneous opening of 2 dropdowns sharing same directive - javascript

I have an angularjs dropdown directive called X that opens and shows related items when I start typing on an input field. There are two X directives in my page which have the same controller and template (ie same directive but different isolated scope).
The first directive shows list of planets and the second shows list of minerals in the planet that is being typed. When I start typing on an input, I want to open both directive showing related data dynamically. But as they share same template, I don't know how to open the dropdown for the second directive.
There is a single ng-repeat in the template but 2 lists on 2 different scopes. I just want to know the approach in understanding this. Thank you.

Here directive will listen inpVal and updates the list in directive (you need to pass inpVal to the directive).
.directive("myCustomSelect", function(){
return {
restrict: "AE",
scope: {
inpVal: "="
},
link: function(scope, ele, attrs){
var _list = [];
scope.list = _list;
var _watch = scope.$watch("inpVal", function(n){
if(n){
updateList();
}
});
scope.$on("$destroy", function(){
_watch();
});
function updateList(){
var enteredVal = scope.inpVal;
//_.filter is underscore js
scope.list = _.filter(_list, function(v){
return enteredVal == v.name?true:false;
});
}
},
template: "<select ng-options="l.name as l for l in list"></select>"
}
})

Related

AngularJS doesn't parse dynamically loaded data from directive

I am trying to create N number of Select controls dynamically from directive based on array that is passed in from the attribute (where N is the length of the array).
Structure of an object of the array is as such:
selectDescription = {
array: arrayObject, //ng-options, a string as 'item as item.name for item in selectArray[0]'
change: methodName, //ng-change, actionname
level: levelNumber //level number
}
So the number of select controls inside span tag depends on the number of selectDescription(s) that I get from the attribute.
First select control is rendered successfully. Subsequent select controls should have been rendered on select of an option from previous rendered select controls. But it's not happening in my case. Although I am successfully appending angular elements in the current inputEl(on select of an option), it is not being rendered in the UI. I guess I am missing something very crucial.
On change of selectDescriptions, a flipped attribute is set, through which I am able to call scope.$editable.render() from link, which in turn runs render function to re-append elements after clearing the previous HTML inside span.
My Code:
app.directive('editableLocation', function(editableDirectiveFactory) {
var createElement = function(el, index){
var newElement = angular.element("<select/>");
newElement.attr('ng-model','$data'+index);
newElement.attr('ng-options',el.array);
newElement.attr('ng-change',el.change.substring(0, el.change.length - 1)+", $data"+index+")");
return newElement;
}
var descriptions = [] ;
var dir = editableDirectiveFactory({
directiveName: 'editableLocation',
inputTpl: '<span></span>',
render: function() {
this.parent.render.call(this);
this.inputEl.html("");
for(var i = 0 ; i < descriptions.length ; i ++){
this.inputEl.append(createElement(descriptions[i], i));
}
}
});
var linkOrg = dir.link;
dir.link = function(scope, el, attrs, ctrl) {
console.log(el);
descriptions = scope.$eval(attrs.description);
scope.$watch('flipped',function(newValue,oldValue){
if(newValue != 0){
scope.$editable.render();
}
});
return linkOrg(scope, el, attrs, ctrl);
};
return dir;
});
Since you are adding the dynamic HTML content in the link function of the Angular directive, Angular will not auto compile/parse it. You need to do it manually using $compile directive. So after you appended all the HTML, do the following (inject $compile in your code)
$compile(element.contents())(scope);
Where element is your any parent element where you are generating dynamic HTML and scope is the scope of the directive or any other scope which you want it to be attached to the dynamic HTML.
Looking at xeditable.js I have found that xeditable renders the UI by calling a show method defined in its editableController.
It is defined as:
self.show = function() {
self.setLocalValue();
self.render(); //calls 'render' function of 'editableDirectiveFactory'; that' where my custom UI lies
$element.after(self.editorEl); //attaches newelement(especially whole <form/> element)
$compile(self.editorEl)($scope); //renders whole UI(and also the newly attached one)
self.addListeners();
$element.addClass('editable-hide');
return self.onshow();
};
So what I felt is, I need to call this show method from my link function, which receives the controller.
This is what I did:
dir.link = function (scope, el, attrs, ctrl) {
$element = el;
scope.$watch(attrs.flipped, function (newValue, oldValue) {
//re-render element if flipped is changed; denoting description of select controls have been altered
if (newValue != 0) {
ctrl[0].show(); //this will call render function and also $compile({{content/html/element}})(scope)
}
});
return linkOrg(scope, el, attrs, ctrl);
};
And also you need to hide the previous <form/> element(which contains previous rendered UI), so that only one forms get displayed.
This is how I hid that previous <form/> element in render' function ofeditableDirectiveFactory`:
var prevForm = $element[0].nextElementSibling; //hide previous form element which would already contain previous select
if (prevForm)
prevForm.classList.add('editable-hide');
That solved my problem at least :)

AngularJS directive restrict

I made some AngularJS directives in the past week and they all work but this one just won't work and I don't know what I am doing wrong..
This is the directive I'm talking about:
app.directive('idleCheck', [function () {
return {
restrict: 'I',
link: function (scope, elem, attrs) {
ifvisible.setIdleDuration(5);
ifvisible.on("idle", function () {
var div = document.getElementById('fullscreenWrap');
div.style.cursor = 'none';
stream.pause();
});
ifvisible.on("wakeup", function () {
var div = document.getElementById('fullscreenWrap');
div.style.cursor = 'auto';
stream.resume();
});
}
}
}]);
This is my HTML code where I call the directive:
<div id="fullscreenWrap" idle-check>
...
</div>
Do you see anything wrong in the code ?
Or do you know why it isn't working ?
You need to change restrict field to 'A'.
The restrict option is typically set to:
'A' - only matches attribute name 'E' - only matches element name 'C'
- only matches class name These restrictions can all be combined as needed:
'AEC' - matches either attribute or element or class name
Angular directive
The restrict options available are: 'E','A','C','M'
One of EACM restricts the directive to a specific directive declaration style.
You can even use Multiple restrictions on same directive restrict: 'AC'
If you don't restrict any, the defaults (elements and attributes) are used.
E - Element name (default): <my-directive></my-directive>
A - Attribute (default): <div my-directive="exp"></div>
C - Class: <div class="my-directive: exp;"></div>
M - coMment: <!-- directive: my-directive exp -->
For Example:
ng-if is restricted to 'A'. so it can be used only as attribute, you can't use as comment or element
Here's the angularjs code for ngIf
var ngIfDirective = ['$animate', function($animate) {
return {
transclude: 'element',
priority: 600,
terminal: true,
restrict: 'A', // --> This means restricting to Attribute
Without knowing what error it is actually giving your issue is most likely your directive declaration.
There is no restrict: I. Angular only supports three values for this:
A - only matches attribute name
E - only matches element name
C - only matches class name
You can but any combination of the three though to support multiple cases.
Docs: https://docs.angularjs.org/guide/directive#template-expanding-directive
It states the info at the bottom of the template expanding directive section.

$compile in Directives

Hey guys i was planning out a directive i was making which would essentially be a popup with a timer on it. Basically the plan was to pass in an object which could configure the properties to construct the message. The directive would contain the html template and we would append the message/html based on the properties set in a service. For Example:
$rootScope.timer = 'recursive time fn goes here'
obj = {
message : '<span ng-click="connect()">Custom message goes here {{ timer }} </span>'
}
Popup.pop(obj);
etc. The point of the question is the $rootScope timer needs to tick down (which is simple to do in a controller) but the directive sets html as a string if interpolated and will not update the value if i'm correct. My question is how do i get the directive to render the timer ticking down inside the directive. would i need to use $compile in the directive? if so how? Furthermore how would i pass an ng-click function from this service if i ever needed one? Sorry if its confusing pls ask questions.
Try this
//you can add your custom messge and time function returning value to the way u want
// this is the basic way to do
var testing = angular.module('testing', [])
testing.directive('mydir', function ($compile, $rootScope) {
var template = '<span ng-click="connect()">custom message</span>'
return {
restrict: 'E',
link: function (scope, ele, attribute) {
scope.connect = function () {
alert('popup' + new Date().getTime());
}
var content = $compile(template)(scope);
ele.append(content)
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body>
<div ng-app="testing">
<mydir></mydir>
</div>
</body>

Nested directives/controllers in angular

Just getting my head around Angular - failing to understand a few concepts as I come from the Backbone school of thought.
I've picked a random project to get started: a card game.
Let's say that I wanted to define a hand controller and a card controller. For simplicity, I want to have them as directives.
Here is the card directive:
app.directive('card', function(){
return {
restrict:'E',
templateUrl:'card.html',
controller:function($scope){
this.suit = 'clubs';
this.rank = 'a';
this.suitClass = function(){
return this.suit + '-' + this.rank;
}
},
controllerAs:'card'
};
});
And here is the hand directive:
app.directive('hand', function(){
return {
restrict:'E',
template:'hand.html',
controller:function($scope){
this.cards = [
{suit:'clubs', rank:'a'},
{suit:'spades', rank:'10'},
{suit:'hearts', rank:'2'},
{suit:'diamonds', rank:'k'}
];
},
controllerAs:'hand'
}
});
With the following plunker, I was expecting to be able to simply drop in the <hand></hand> element and have angular do all the work for me. In my minds eye there should be cards representing different suits nested within the <hand> directive. What am I missing? Currently, as you can tell in the plunker, the nested controller/directive does not instantiate the view properly.
Am I thinking in too much of an MVC way? Is OOP haunting me? Or is angular just badly designed?
I am not 100% sure that I understand your question but I think that this is a better way to write it:
var app = angular.module('app', []);
app.directive('card', function(){
return {
restrict:'E',
templateUrl:'card.html',
replace: true,
link: function ($scope, element, attrs){
$scope.suit = 'clubs';
$scope.rank = 'a';
$scope.suitClass = function(){
return this.suit + '-' + this.rank;
}
}
};
});
app.directive('hand', function($compile){
return {
restrict:'E',
templateUrl:'hand.html',
link:function($scope, element, attrs){
$scope.cards = [
{suit:'clubs', rank:'a'},
{suit:'spades', rank:'10'},
{suit:'hearts', rank:'2'},
{suit:'diamonds', rank:'k'}
];
}
}
});
And the html can be something like these:
(hand directive template)
<div>
<card ng-repeat="card in cards"></card>
</div>
And (card directive template)
<div ng-class="card.suitClass()">
{{ suit }}
</div>
I will explain the problem by going top down through the order of elements/objects that will be called:
hand directive:
The directive is ok so far. But the $compile parameter and the $scope parameter are not used an should be removed. To be more clear I applied this to a variable hand, but it does not change the behaviour of the application.
app.directive('hand', function(){
return {
restrict:'E',
templateUrl:'hand.html',
controller:function() {
var hand = this;
hand.cards = [
{suit:'clubs', rank:'a'},
{suit:'spades', rank:'10'},
{suit:'hearts', rank:'2'},
{suit:'diamonds', rank:'k'}
];
},
controllerAs:'hand'
}
});
hand.html:
You never passed the current card of the ng-repeat to the card directive.
That way you only produce the card templates times the number of card but never using the actual values.
I removed the obsolete div tag and enhanced the hand.html to this:
<card ng-repeat="card in hand.cards" card-model="card"></card>
This way I get every card from the hand view in the card directive.
card directive:
First I remove the $scope variable because it is never used and won't be used here.
This function is rather incomplete. At least it is missing the card values you want to use. But a major problem in here is that the context of this is bound to the caller. To be more precise, you are using this inside of the suitClass function, but you want to use the suit and rank values of the controller. this does not point to the controller function but to the newly created suitClass function which doesn't know any of these values. For that problem you should introduce a variable that holds the context and access the values that way. And I add the scope variable cardModel that is bound to the element attribute to get the desired values. And I add the bindToController: true to access the passed in model as card.cardModel instead of the pure cardModel:
app.directive('card', function(){
return {
restrict:'E',
scope: {
cardModel: '='
},
templateUrl:'card.html',
controller:function(){
var card = this;
console.log(card.cardModel)
card.suitClass = function(){
return card.cardModel.suit + '-' + card.cardModel.rank;
}
},
controllerAs:'card',
bindToController: true
};
});
card.html:
This view is okay. I only applied my changes:
<div ng-class="card.suitClass()">{{ card.cardModel.rank }}</div>
I hope it is still useful for anybody.

Angularjs how to pass in data using a directive

What I am trying to do is make a function so I can change the height of my ng-grid column width. That is irrelevant besides the fact that the scope from my controller needs to communicate with the scope in my directive.
.directive('getWidth', function(){
return{
controller: 'QuotesCtrl',
link: function(scope){
scope.smRowHeight = function(the value i want){
scope.theRowHeight = the value i want;
}
}
}
})
And I just want to be able to go into my html and say hey for this div I want the height 20
<div getWidth = '20'></div>
I have looking around and I couldn't find anything doing with this exact thing. and by the way, in my QuotesCtrl i initialized the row height like so
$scope.theRowHeight;
Any suggestions?
Try something like this:
.directive('getWidth', function(){
return{
controller: 'QuotesCtrl',
link: function(scope){
console.log(scope.theRowHeight);
},
scope: {
'theRowHeight': '='
}
}
});
Markup:
<div the-row-height="20"></div>
Directives are amazing! You can pass in what is called an isolate scope, and with that you can pass in values as strings or references to your controller scope. There are 3 options on the isolate scope that you should look into. = # & See the link below the example to the docs.
Here is a working JSFiddle
.directive('getHeight', function(){
return{
scope: {
"rowHeight": '='
},
controller: 'QuotesCtrl',
link: function(scope){
scope.smRowHeight = function(the value i want){
scope.theRowHeight = the value i want;
}
}
}
})
You would need to update your html to pass in the new scope value.
<div get-height row-height='20'></div>
More Info on Directives

Categories

Resources