Angular - Passing variables to the directive scope - javascript

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);
}
};
});

Related

Resolving scope variables in an angular directive

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);
},
};
});

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.

AngularJs: Calling contoller method from directive inside another directive

I have a directive inside another directive. Outer directive shares its scope with controller, while inner one has its own. I'd like to pass a reference to controller's function to inner directive so it can be called from there. But I cannot figure out how to pass the function and its parameters to inner directive so it can properly call the controller's function.
Here is planker to illustrate my problem.
If you click on "Dir 2 Click me" the alert says the parameters have came undefined.
You can pass in the outer controller method using '=' and adjust the code accordingly...
angular.module('app', [])
.controller('ctrl', function($scope){
$scope.myCtrlMethod = function(msg, b) {
alert(msg + ' and b='+b);
};
})
.directive('dir1', [function(){
return {
restrict: 'E',
replace: true,
template: '<div><p ng-click="myDir1Method(\'my dir1 method\',\'b\')">Dir 1 Click me</p><dir2 my-ctrl-method="myCtrlMethod"></dir2></div>',
link: function(scope, elem, attrs){
scope.myDir1Method = function(msg,b){
scope.myCtrlMethod(msg, b);
};
}
};
}])
.directive('dir2', [function(){
return {
restrict: 'E',
scope: {
myCtrlMethod: '='
},
replace: true,
template: '<p ng-click="myDir2Method(\'my dir2 method\',\'b\')">Dir 2 Click me</p>',
link: function(scope, elem, attrs){
scope.myDir2Method = function(msg,b){
scope.myCtrlMethod(msg, b);
};
}
};
}]);
Plunker: http://plnkr.co/edit/xbSNXaSmzWa3G1GSH6Af?p=preview
Edit: '=' evaluates the expression in the context of the parent scope and its result is bound to the property on the inner scope. In this example, 'myCtrlMethod' is evaluated against the parent scope, which returns myCtrlMethod from the parent scope (a function). This function is bound to myCtrlMethod on the inner scope, and can be invoked with scope.myCtrlMethod(msg, b).
you can use controller as a reference to your directive
See: http://jsbin.com/vayij/1/edit
directive('sonDirective', function(){
return {
restrict: 'E'
scope: {},
replace: true,
template: '<div....'
controller: 'MainController' //controller as a reference
}
})
Just put the controller on the scope : $scope.$b=this;
See : http://plnkr.co/edit/skDF8D1scFJYrTUmcXIL?p=preview

How do I pass an object to a directive?

I'm having issues getting an object to pass to my directive. I believe I've done things correctly, but after failed attempt after failed attempt I must seek help. What did I miss here that's stopping me from passing an array to my directive?
HTML:
<div class="body">
{{orderList.length}} //shows up as 18
</div>
<queue-summary orders="orderList"></queue-summary>
Javascript:
directive('queueSummary', function () {
return {
scope: {
orders: '='
},
replace: true,
restrict: 'E',
templateUrl: '/partials/admin/bits/queue-summary.htm',
link: function (scope, element, attrs) {
console.log(scope, element, attrs); //$attrs.orders show it as the String "orderList" instead of the array
}
}
}).
It's worth noting that you can access the bound value of an attribute you don't have isolate scope on with $eval:
scope.$eval(attrs.orders)
attrs will just show you the string value of an attribute. In order to access the passed object, use the isolate binding you created:
console.log(scope.orders);

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