Resolving scope variables in an angular directive - javascript

I'm working on creating an angular directive (element) that will apply some transformation to the text within.
Here is the directive:
module.directive('myDir', function() {
return {
restrict: 'E',
link: function(scope, elem, attrs) {
console.log(elem.text());
},
};
});
For now I've just placed a console.log in there to make sure I am seeing the expected text.
If my html is like this it works as expected:
<my-dir>Hello World!</my-dir>
However, if I use a variable from the scope such as this:
<my-dir>{{myMessage}}</my-dir>
Then that is the text I seen in the console output instead of the variables value. I think I understand why the output is this way, however I'm not sure how to get the correct value. The requirement is that the directive should be able to transform text from both examples.
Thoughts?

Use $interpolate service to convert the string to a function, and apply the scope as parameter to get the value (fiddle):
module.directive('myDir', function($interpolate) {
return {
restrict: 'E',
link: function(scope, elem, attrs) {
console.log($interpolate(elem.text())(scope));
},
};
});

If you really interested get the interpolated content then do use $interpolate service to evaluated the interpolated content.
Code
link: function(scope, elem, attrs) {
console.log($interpolate(elem.text())(scope));
},
Don't forget to add $interpolate as dependency on directive function.

Have a look on $compile or http://odetocode.com/blogs/scott/archive/2014/05/07/using-compile-in-angular.aspx
This should work:
module.directive('myDir', function($compile) {
return {
restrict: 'E',
link: function(scope, elem, attrs) {
console.log($compile(elem.text())(scope));
},
};
});

I would suggest you use an isolated scope on directive which will give you access to the value without having to get it from the dom. You will also be able to manipulate it directly in the link function as part of scope
<my-dir my-message="myMessage"></my-dir>
JS
module.directive('myDir', function() {
return {
restrict: 'E',
template: '{{myMessage}}',
scope:{
myMessage: '=',
},
link: function(scope, elem, attrs) {
console.log(scope.myMessage);
},
};
});

Related

How to prevent scope collision between angularjs directives?

I have created a simple directive, called match that is used like:
<input match='pattern' />
The declaration line of my directive is:
app.directive('match', function () {
return {
restrict: 'A',
require: 'ngModel',
scope: {
pattern: '=match'
},
link: function (scope, element, attributes, ngModel) {
// doing stuff here
}
};
});
However, after a while I wanted to use BootstrapUI for angularjs, and as soon as I started using typeahead component, they encountered a problem on using the same scope:
Multiple directives [match, uibTypeaheadMatch] asking for new/isolated scope on
I need match, and typeahead together in one page. Typeahead is not under my control, and I don't want to change match's name.
What can I do to prevent their collision?
The problem is that both your directive and Typeahead directive, are asking for isolated scope on the same element and angular does not allow it.
To overcome this problem, define the directive in a different way:
app.directive('match', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attributes, ngModel) {
var match = attributes.match;
//do your stuff
}
};
});

Trying to load variable into Angular directive

So I am so confused! I have HTML that looks like this:
<span paper-embed="" url="theUrl"></span>
and theUrl is a variable that loads a different URL from my ng-controller. Then I have an Angular directive looks like this:
app.directive('paperEmbed', function() {
return {
restrict: 'AEC',
transclude:true,
scope: {
key: '=',
value: '='
},
link: function(scope, element, attrs) {
// is does some jQuery here
}
};
});
my question is, I want to access the URL inside the directive - the variable named theUrl, so how do I do that? I looked up on SA and seemed like
console.log({{theUrl}});
might work but it does not.
Change your scope to
scope: {
key: '=',
value: '=',
url: '='
},
And in your link function you can use it like scop.url
You can access it with attrs.url
Since you are trying to implement a directive with the following:
<span paper-embed="" url="theUrl"></span>
you should use restrict: 'A',
the url attribute can be accessed either through your scope declaration as # or through the attrs object passed into your link function.
as to the console.log({{theUrl}}). {{}} is specifically design to interpolate javascript-keys in the markup, that is processed through the $compile cycle.
Here is something to get you started:
HTML
<span paper-embed url="http://example.com" />
javascript
var app = angular.module('exampleApp', []);
app.directive('paperEmbed', function() {
return function(scope, elem, attrs) {
console.log(attrs.url);
};
});
get a little more detailed information here: https://docs.angularjs.org/api/ng/service/$compile#directive-definition-object
You can either use attrs.url to access it or you can add the url to the scope:
app.directive('paperEmbed', function() {
return {
restrict: 'AEC',
transclude:true,
scope: {
key: '=',
value: '=',
url: '#'
},
link: function(scope, element, attrs) {
console.log(scope.url);
}
};
Whenever you add a variable to the scope like above, the directive is expecting an html attribute to supply that value. In this case url.
<div paper-embed="obj1" key="obj2" value="obj3" url="obj4"></div>
scope.url === obj4;
Among many others, there are two easy ways to do this:
- First method is to access it using the attrs.
- Second method is to pass the parameters by defining in the scope.
First method is to use attrs. attrs has all the attributes. You can simply access the url in the link function as attrs.url
link:function(scope,element,attrs){
console.log(attrs.url)
}
You will see whatever is placed instead of theUrl is displayed on the console.
The other alternative is to change your directive to the following:
app.directive('paperEmbed', function() {
return {
restrict: 'AEC',
transclude:true,
scope: {
key: '=',
value: '=',
theUrl: '='
},
link: function(scope, element, attrs) {
// is does some jQuery here
}};});
Now you can access it in the link function as scope.url. To set the value to be passed simply set $scope.theUrl='whatever your url is' in your ng-controller.

How to pass the angular's directive's link and controller to it

Say that I have a straight forward directive:
angular
.module('myApp')
.directive('myDiv', ['MyService1', 'MyService2',
function(MyService1, MyService2) {
return {
restrict: 'E',
link: function(scope, element, attrs) {
scope.myVars = MyService1.generateSomeList();
MyService2.runSomeCommands();
// Do a lot more codes here
// Lines and Lines
// Now run some embedded function here
someEmbeddedFunction();
function someEmbeddedFunction()
{
// More embedding
// This code is really getting nasty
}
}
}
}
]);
The code above has so much indentation and crowded that at least to me, it is very hard to read and unenjoyable to work with.
Instead, I want to move the link and someEmbeddedFunction out and just call them. So something along the lines of this:
function link(scope, element, attrs, MyService1, MyService2)
{
scope.myVars = MyService1.generateSomeList();
MyService2.runSomeCommands();
// Do a lot more codes here
// Lines and Lines
// Now run some embedded function here
someEmbeddedFunction();
}
function someEmbeddedFunction()
{
// This is much nicer and less tabbing involved
}
angular
.module('myApp')
.directive('myDiv', ['MyService1', 'MyService2',
function(MyService1, MyService2) {
return {
restrict: 'E',
link: link // This is line that I need to get it to work
}
]);
The problem is that MyService1 and MyService2 are not passed to the link function (i.e. if I only had a link function with scope, element, attrs then the code above would work just fine). How can I pass those variables as well?
I tried to call the function as link: link(scope, element, attrs, MyService1, MyService2) but then it says scope, element, attrs are undefined.
Note I realize that the someEmbeddedFunction can right now be moved out without a problem. This was just for demonstrating purposes.
Edit
The only way I can think to get this to work is call the link function from the directive this way:
link: function(scope, element, attrs) {
link(scope, element, attrs, MyService1, MyService2);
}
As you observed, the only way to call your non-standard link function is to do so manually within a "standard" link function.
i.e.
link: function(scope, element, attrs) {
link(scope, element, attrs, MyService1, MyService2);
}
This is because the link function doesn't get injected like other functions in Angular. Instead, it always gets the same series of arguments (regardless of what you call the function parameters):
The scope
The element (as an angular.element() instance)
The attrs object
An array or single controller instance that you required
A transclude function (if your directive uses transclusion)
Nothing else.
I use this scheme to keep it simple & readable:
var awesomeDir = function (MyService, MyAnotherService) {
var someEmbeddedFunction = function () {
MyService.doStuff();
};
var link = function ($scope, $elem, $attrs) {
someEmbeddedFunction();
};
return {
template: '<div>...</div>',
replace: true,
restrict: 'E',
link: link
};
};
awesomeDir.$inject = ['MyService', 'MyAnotherService'];
app.directive('awesomeDir', awesomeDir);

Angular - Passing variables to the directive scope

I would like to pass an object to the directive scope:
JS:
app.directive('validatePrice', function() {
return {
link: function(scope, el, attrs){
console.log(attrs.validatePrice);
}
};
});
HTML
<button validate-price="{priceValid: {'disabled': 'disabled'}}">Checkout</button>
where priceValid is a boolean from the controller scope and {'disabled': 'disabled'} is just a plain object. I expect my attrs.validatePrice to return eg:
{
true: {'disabled': 'disabled'}
}
Yet it returns string. How do I do that? :)
I don't think what you want is possible. priceValid will be interpreted as an object key by JavaScript – it will not be interpreted as true.
Anyway, $parse or $eval is what you need to use to pass an object to a directive (if you are not using an isolated scope):
<button validate-price="{priceValid: {'disabled': 'disabled'}}">Checkout</button>
app.directive('validatePrice', function($parse) {
return {
link: function(scope, el, attrs){
var model = $parse(attrs.validatePrice);
console.log(model(scope));
console.log(scope.$eval(attrs.validatePrice));
}
};
});
fiddle
Use $parse if you need to alter the object. See https://stackoverflow.com/a/15725402/215945 for an example of that.
<validate-price-dir validate-price="{priceValid: {'disabled': 'disabled'}}">Checkout</validate-price-dir>
app.directive('validatePriceDir', function() {
return {
restrict: 'E',
scope: { validatePrice: '=validatePrice' },
link: function(scope, el, attrs){
console.log(scope.validatePrice);
}
};
});

Modify template in directive (dynamically adding another directive)

Problem
Dynamically add the ng-bind attribute through a custom directive to be able to use ng-bind, ng-bind-html or ng-bind-html-unsafe in a custom directive with out manually adding to the template definition everywhere.
Example
http://jsfiddle.net/nstuart/hUxp7/2/
Broken Directive
angular.module('app').directive('bindTest', [
'$compile',
function ($compile) {
return {
restrict: 'A',
scope: true,
compile: function (tElem, tAttrs) {
if (!tElem.attr('ng-bind')) {
tElem.attr('ng-bind', 'content');
$compile(tElem)
}
return function (scope, elem, attrs) {
console.log('Linking...');
scope.content = "Content!";
};
}
};
}]);
Solution
No idea. Really I can not figure out why something like the above fiddle doesn't work. Tried it with and with out the extra $compile in there.
Workaround
I can work around it might adding a template value in the directive, but that wraps the content in an extra div, and I would like to be able to that if possible. (See fiddle)
Second Workaround
See the fiddle here: http://jsfiddle.net/nstuart/hUxp7/4/ (as suggested by Dr. Ikarus below). I'm considering this a workaround for right now, because it still feels like you should be able to modify the template before you get to the linking function and the changes should be found/applied.
You could do the compiling part inside the linking function, like this:
angular.module('app').directive('bindTest', ['$compile', function ($compile) {
return {
restrict: 'A',
scope: true,
link: {
post: function(scope, element, attrs){
if (!element.attr('ng-bind')) {
element.attr('ng-bind', 'content');
var compiledElement = $compile(element)(scope);
}
console.log('Linking...');
scope.content = "Content!";
}
}
};
}]);
Let me know how well this worked for you http://jsfiddle.net/bPCFj/
This way seems more elegant (no dependency with $compile) and appropriate to your case :
angular.module('app').directive('myCustomDirective', function () {
return {
restrict: 'A',
scope: {},
template: function(tElem, tAttrs) {
return tAttrs['ng-bind'];
},
link: function (scope, elem) {
scope.content = "Happy!";
}
};
});
jsFiddle : http://jsfiddle.net/hUxp7/8/
From Angular directive documentation :
You can specify template as a string representing the template or as a function which takes two arguments tElement and tAttrs (described in the compile function api below) and returns a string value representing the template.
The source code tells all! Check out the compileNodes() function and its use of collectDirectives().
First, collectDirectives finds all the directives on a single node. After we've collected all the directives on that node, then the directives are applied to the node.
So when your compile function on the bindTest directive executes, the running $compile() is past the point of collecting the directives to compile.
The extra call to $compile in your bindTest directive won't work because you are not linking the directive to the $scope. You don't have access to the $scope in the compile function, but you can use the same strategy in a link function where you do have access to the $scope
You guys were so close.
function MyDirective($compile) {
function compileMyDirective(tElement) {
tElement.attr('ng-bind', 'someScopeProp');
return postLinkMyDirective;
}
function postLinkMyDirective(iScope, iElement, iAttrs) {
if (!('ngBind' in iAttrs)) {
// Before $compile is run below, `ng-bind` is just a DOM attribute
// and thus is not in iAttrs yet.
$compile(iElement)(iScope);
}
}
var defObj = {
compile: compileMyDirective,
scope: {
someScopeProp: '=myDirective'
}
};
return defObj;
}
The result will be:
<ANY my-directive="'hello'" ng-bind="someScopeProp">hello</ANY>

Categories