AngularJS : Passing attribute value from one directive to transcluded one - angularjs

I have a situation where I have to create a container directive with some bells and whistles.. and then I have a list of directives that can be wrapped into that container directive.
Something like this:
<the-container foo="bell" bar="whistle">
<some-directive></some-directive>
</the-container>
<the-container foo="potato" bar="tomato">
<some-other-directive></some-other-directive>
</the-container>
Is there any way in which I can make <some-directive> and <some-other-directive> aware of the foo and/or bar attributes values of the directive they are transcluded in?
Basic theContainer directive
.directive("theContainer", function() {
return {
restrict: "E",
replace: true,
transclude: true,
scope: true,
templateUrl: "theContainer.html",
compile: function(element, attrs) {
return function(scope, element, attrs) {
scope.containerAttrs = {
foo: attrs.foo,
bar: attrs.bar
};
};
}
}
});
Let's presume that these two directives have different and unrelated function all together
someDirective
.directive("someDirective", function() {
return {
restrict: "E",
scope: true,
templateUrl: "someDirective.html",
controller: function($scope, $element, $attrs) {},
compile: function(element, attrs) {
return function(scope, element, attrs) {
// I need the value from theContainer foo and bar here
// or anywhere in this directive for starters
foo = 'bells';
bar = 'whistles';
};
}
}
});
someOtherDirective
.directive("someOtherDirective", function() {
return {
restrict: "E",
scope: true,
templateUrl: "someOtherDirective.html",
controller: function($scope, $element, $attrs) {
// I need the value from theContainer foo and bar here
// or anywhere in this directive for starters
foo = 'potato';
bar = 'tomato';
}
}
});

Scopes in angular by default inherit from parent scope. Unfortunately, with angular default transclusion, there is no child/parent relationship between container and transcluded content.
You could try custom transclusion.
compile: function(element, attrs, linker) {
return function(scope, element, attrs) {
scope.containerAttrs = {
foo: attrs.foo,
bar: attrs.bar
};
linker(scope, function(clone) { //bind scope anyway you want
element.append(clone); // add to DOM anywhere you want
});
};
}
Note: remember to remove ng-transclude in your template when you do custom transclusion,
DEMO

Related

Get directions childs tags AngularJS

i made this directive that i call in my html like
<my-datepicker />
what i want to do now, is to expend it, so that i can do something like this
<my-datepicker >
<my-day>{{date}}</my-day>
<my-month>{{moth}}</my-month>
<my-year>{{year}}</my-year>
</my-datepicker>
resulting in my-datepicker directive can get the child elements.
how can you do this? do you need to make the childs like standanlone directive, an how can you get the value from them in the parent(my-datepicker) directive
You can access parent directive controller like this:
app.directive('myDay', function () {
return {
restrict: 'E',
require: '^myDatepicker',
link: function (scope, element, attrs, parentCtrl) {
parentCtrl.doSomething();
}
};
});
In parent:
app.directive('myDatepicker', function () {
return {
restrict: 'E',
controller: function () {
this.doSomething = function () {
alert('Do something in parent');
};
}
};
});
I think the best way to extend your directive is by passing parameters (date month ec... ) as attributes.
Your html should be somethig like this
<my-datepicker day="day" month="month" year="year"/>
Inside your directive you should be able to retrieve those variables by declaring them in the scope.
function myDatepicker() {
var directive = {
templateUrl: 'yourtemplate.html',
restrict: 'E',
link: link,
scope: {
date: '=',
month: '=',
year: '='
}
}
return directive;
function link(scope, element, attrs) {
// use here scope.date scope.month and scope.year
}
};

Nested and dynamically created directives in angular.js

I am stuck with this for quite a long time.
In a directive, I would like to create another directive on the fly, based on a function. Instead of having 4 directive declarations, I would prefer to create a new directive in each 'tab' directive, that is to say each time a tab attribute is set in a DOM element.
Here is a part of the code (config is a factory that is use to configure some stuff) :
.directive('tab', function(config) {
return {
require: '^panelHandler',
restrict: 'A',
scope: true,
link: function(scope, elem, attrs, ctrl) {
ctrl.addPane(scope);
scope.select = function() {
ctrl.select(scope);
};
},
};
})
.directive('page1', directiveConfigurer('page1.html'))
.directive('page2', directiveConfigurer('page2.html'))
.directive('page3', directiveConfigurer('page3.html'))
.directive('page4', directiveConfigurer('page4.html'));
function directiveConfigurer(fileName) {
newDirective.$inject = ['config'];
return newDirective;
function newDirective(config) {
var directive = {
restrict: 'E',
scope: true,
templateUrl: config.filesDirectory + fileName,
};
return directive;
}
}
Thanks for your help.
EDIT :
Config...
angular.module('appLogic', ['socket-factory', 'data-factory', 'panelHandler-module'])
.factory('config', function() {
return {
filesDirectory : '../../templates/pages/',
fieldsNumber : 5,
};
});
and what I need...
link: function(scope, elem, attrs, ctrl) {
ctrl.addPane(scope);
//.directive('page' + number, directiveConfigurer(name))
scope.select = function() {
ctrl.select(scope);
};
},
If the directives are essentially the same, except for the template url, then you can just create a single directive and provide the concrete url path as an attribute:
<page src="page1.html">
To do that, use a function for templateUrl property of the directive definition object:
.directive("page", function(){
return {
templateUrl: function(tElem, tAttr){
return "/base/path/" + tAttr.src;
},
//...
};
});

Dynamic controller

I have two nested directive and a few controllers and I want inject controller to second controller.
When I bind action to some button it work but list don't show up, some one know why?
Dynamic Controller directive
.directive("dynamicController", ["$compile", function($compile) {
return {
restrict: "A",
scope: {
dynamicController: "#"
},
compile: function(tElement, tAttrs) {
return {
pre: function preLink(scope, iElement, iAttrs, controller) {
iElement.attr("ng-controller", scope.dynamicController);
iElement.removeAttr("dynamic-controller");
$compile(iElement)(scope);
}
}
}
}
}])
V1: http://codepen.io/anon/pen/LVeaWo
V2: http://codepen.io/anon/pen/EjoJVx
[ EDIT ]
I almost do it but it's one more problem.
I have two directive:
.directive("wrapDirective", function() {
return {
restrict: "A",
template: "<div dynamic-controller=\"Ctr1\">" +
"<button ng-click='action()'>Click</button>" +
"<ul>" +
"<li ng-repeat=\"item in list\">{{item}}</li>" +
"</ul>" +
"</div>",
scope: {
controller: "#wrapDirective"
}
}
})
and
.directive("dynamicController", function($compile) {
return {
restrict: "A",
scope: true,
controller: "#",
name: "dynamicController"
}
})
The problem is this line <div dynamic-controller=\"Ctr1\"> in warpDirective
I can't do something like this <div dynamic-controller=\"{{controller}}\">
CodePen with both cases: http://codepen.io/anon/pen/EjoJXV
You should use require and link to get the controllers of parent directives.
See Creating Directives that Communicate.
.directive('myDirective', function() {
return {
require: '^ngController', // <-- define parent directive
restrict: 'E',
scope: {
title: '#'
},
link: function(scope, element, attrs, ctrl) { // <-- get the controller via the link function
ctrl.doSomething();
}
};
The reason behind your code is not working is, {{}} interpolation value is not evaluated in you pre link function. So by compiling ng-controller with not value in it is throwing an error. You should use iAttrs.$observe as you are evaluating expression inside {{}}.
Code
var dynamicControllerObserver = iAttrs.$observe('dynamicController', function(newVal, oldVal) {
wrapElement.attr("ng-controller", scope.dynamicController);
wrapElement.append(iElement.html());
console.log(wrapElement)
iElement.html("");
console.log(iElement)
iElement.append(wrapElement);
$compile(wrapElement)(scope);
dynamicControllerObserver(); //destruct observe
})
Working Codepen
I did it, really helpful was this post: Dynamic NG-Controller Name
I modified it to my needs:
.directive('dynamicCtrl', ['$compile', '$parse', function($compile, $parse) {
return {
restrict: 'A',
terminal: true,
scope: {
dynamicCtrl: "#"
},
link: function(scope, elem, attr) {
var initContent = elem.html();
var varName = getName(elem.attr('dynamic-ctrl'));
update();
scope.$watch("dynamicCtrl", function() {
update();
})
function update() {
var wrapper = angular.element("<div></div>");
wrapper.append(initContent);
var name = $parse(varName)(scope.$parent);
wrapper.attr('ng-controller', name);
elem.empty();
elem.append(wrapper);
$compile(wrapper)(scope);
}
function getName(attr) {
var startIndex = attr.lastIndexOf("{") + 1,
endIndex = attr.indexOf("}");
return attr.substring(startIndex, endIndex);
}
}
};
}])
http://codepen.io/anon/pen/xGYyqr

How to bind content of tag into into directive's scope?

Say I have a directive like such:
<my-directive>This is my entry!</my-directive>
How can I bind the content of the element into my directive's scope?
myApp.directive('myDirective', function () {
return {
scope : {
entry : "" //what goes here to bind "This is my entry" to scope.entry?
},
restrict: "E",
template: "<textarea>{{entry}}</textarea>"
link: function (scope, elm, attr) {
}
};
});
I think there's much simpler solution to the ones already given. As far as I understand, you want to bind contents of an element to scope during initialization of directive.
Given this html:
<textarea bind-content ng-model="entry">This is my entry!</textarea>
Define bind-content as follows:
directive('bindContent', function() {
return {
require: 'ngModel',
link: function ($scope, $element, $attrs, ngModelCtrl) {
ngModelCtrl.$setViewValue($element.text());
}
}
})
Here's a demo.
I may have found a solution. It relies on the transclude function of directives. It works, but I need to better understand transclusion before being sure this is the right way.
myApp.directive('myDirective', function() {
return {
scope: {
},
restrict: 'E',
replace: false,
template: '<form>' +
'<textarea ng-model="entry"></textarea>' +
'<button ng-click="submit()">Submit</button>' +
'</form>',
transclude : true,
compile : function(element,attr,transclude){
return function (scope, iElement, iAttrs) {
transclude(scope, function(originalElement){
scope.entry = originalElement.text(); // this is where you have reference to the original element.
});
scope.submit = function(){
console.log('update entry');
}
}
}
};
});
You will want to add a template config to your directive.
myApp.directive('myDirective', function () {
return {
scope : {
entry : "=" //what goes here to bind "This is my entry" to scope.entry?
},
template: "<div>{{ entry }}</div>", //**YOU DIDN'T HAVE A TEMPLATE**
restrict: "E",
link: function (scope, elm, attr) {
//You don't need to do anything here yet
}
};
});
myApp.controller('fooController', function($scope){
$scope.foo = "BLAH BLAH BLAH!";
});
And then use your directive like this:
<div ng-controller="fooController">
<!-- sets directive "entry" to "foo" from parent scope-->
<my-directive entry="foo"></my-directive>
</div>
And angular will turn that into:
<div>THIS IS MY ENTRY</div>
Assuming that you have angular setup correctly and are including this JS file onto your page.
EDIT
It sounds like you want to do something like the following:
<my-directive="foo"></my-directive>
This isn't possible with ELEMENT directives. It is, however, with attribute directives. Check the following.
myApp.directive('myDirective', function () {
return {
template: "<div>{{ entry }}</div>", //**YOU DIDN'T HAVE A TEMPLATE**
restrict: "A",
scope : {
entry : "=myDirective" //what goes here to bind "This is my entry" to scope.entry?
},
link: function (scope, elm, attr) {
//You don't need to do anything here yet
}
};
});
Then use it like this:
<div my-directive="foo"></div>
This will alias the value passed to my-directive onto a scope variable called entry. Unfortunately, there is no way to do this with an element-restricted directive. What is preventing it from happening isn't Angular, it is the html5 guidelines that make what you are wanting to do impossible. You will have to use an attribute directive instead of an element directive.

Angularjs: set parent directive scope value with child directive

I'm not sure this is the way to do this, but my goal is the following:
I have a parent directive
Inside the parent directive's block, I have a child directive that will get some input from the user
The child directive will set a value in the parent directive's scope
I can take it from there
Of course the problem is that the parent and child directives are siblings. So I don't know how to do this. Note - I do not want to set data in the
Fiddle: http://jsfiddle.net/rrosen326/CZWS4/
html:
<div ng-controller="parentController">
<parent-dir dir-data="display this data">
<child-dir></child-dir>
</parent-dir>
</div>
Javascript
var testapp = angular.module('testapp', []);
testapp.controller('parentController', ['$scope', '$window', function ($scope, $window) {
console.log('parentController scope id = ', $scope.$id);
$scope.ctrl_data = "irrelevant ctrl data";
}]);
testapp.directive('parentDir', function factory() {
return {
restrict: 'ECA',
scope: {
ctrl_data: '#'
},
template: '<div><b>parentDir scope.dirData:</b> {{dirData}} <div class="offset1" ng-transclude></div> </div>',
replace: false,
transclude: true,
link: function (scope, element, attrs) {
scope.dirData = attrs.dirData;
console.log("parent_dir scope: ", scope.$id);
}
};
});
testapp.directive('childDir', function factory() {
return {
restrict: 'ECA',
template: '<h4>Begin child directive</h4><input type="text" ng-model="dirData" /></br><div><b>childDir scope.dirData:</b> {{dirData}}</div>',
replace: false,
transclude: false,
link: function (scope, element, attrs) {
console.log("child_dir scope: ", scope.$id);
scope.dirData = "No, THIS data!"; // default text
}
};
});
If you want that kind of communication, you need to use require in the child directive. That will require the parent controller so you need a controller there with the functionality you want the children directives to use.
For example:
app.directive('parent', function() {
return {
restrict: 'E',
transclude: true,
template: '<div>{{message}}<span ng-transclude></span></div>',
controller: function($scope) {
$scope.message = "Original parent message"
this.setMessage = function(message) {
$scope.message = message;
}
}
}
});
The controller has a message in the $scope and you have a method to change it.
Why one in $scope and one using this? You can't access the $scope in the child directive, so you need to use this in the function so your child directive will be able to call it.
app.directive('child', function($timeout) {
return {
restrict: 'E',
require: '^parent',
link: function(scope, elem, attrs, parentCtrl) {
$timeout(function() {
parentCtrl.setMessage('I am the child!')
}, 3000)
}
}
})
As you see, the link receives a fourth param with the parentCtrl (or if there is more than one, an array). Here we just wait 3 seconds until we call that method we defined in the parent controller to change its message.
See it live here: http://plnkr.co/edit/72PjQSOlckGyUQnH7zOA?p=preview
First, watch this video. It explains it all.
Basically, you need to require: '^parentDir' and then it will get passed into your link function:
link: function (scope, element, attrs, ParentCtrl) {
ParentCtrl.$scope.something = '';
}

Resources