This is my case -- I have directive with isolated scope and I would like to call function from parent's scope with mixed arguments. Mixed -- meaning, one argument comes from the directive, the other comes from the parent.
In case of arguments coming from directive, I could bind that function with < and use it, in case of arguments coming from parent's scope, I could bind entire function call with &.
I am thinking about two approaches -- one, would simulate currying, call the function with parent's arguments which would return a function accepting directive arguments. Second -- somehow introduce directive variables in the parent's scope, so I could write:
<my-directive on-alarm="emergency(parent_var,dir_var)"/>
I like the second one better. But I don't know how to do it, i.e. how to introduce directive variables into parent's scope -- without doing a manual "reverse" binding, like:
<my-directive for_sake_of_calling="dir_var" on-alarm="emergency(parent_var,dir_var)"/>
But those are more like my guesses -- the main question is: how to call parent's function with mixed arguments?
You can achieve this by doing the following:
First, setup up the main application HTML,
<body ng-app="app">
<div ng-controller="MainCtrl as vm">
Emergency text: {{vm.emergencyText}}
<my-directive on-alarm="vm.emergency(vm.parentVar, directiveVar)"></my-directive>
</div>
</body>
You'll notice that the on-alarm callback contains a reference to the vm.parentVar variable which just refers to MainCtrl.parentVar, and directiveVar which will come from the directive itself.
Now we can create our main controller:
angular.module('app', []);
angular
.module('app')
.controller('MainCtrl', function () {
// Initialise the emergency text being used in the view.
this.emergencyText = '';
// Define our parent var, which is a parameter called to the emergency function.
this.parentVar = 'This is an emergency';
// Define the emergency function, which will take in the parent
// and directive text, as specified from the view call
// vm.emergency(vm.parentVar, directiveVar).
this.emergency = function (parentText, directiveText) {
this.emergencyText = parentText + ' ' + directiveText;
}.bind(this);
});
Finally, we will create the directive.
angular
.module('app')
.directive('myDirective', function () {
return {
scope: {
onAlarm: '&'
},
link: function (scope, element, attrs) {
scope.onAlarm({ directiveVar: 'from myDirective' });
}
}
});
The magic happens after we call scope.onAlarm({ directiveVar: 'from myDirective' });. This call tells angular that the alarm callback function (emergency) will have access to directiveVar, which we referenced earlier in the view through on-alarm="vm.emergency(vm.parentVar, directiveVar)". Behind the scenes, angular will correctly resolve the parentVar scope to MainCtrl and the directiveVar scope to the directive through its $parse service.
Here's a full plunkr.
Related
I have a tree directive and I want when user clicked on some thing happens..it should be implement with who wants to use this tree. for example node's text changes.
index.html
<div ng-controller='TestController'>
<tree model="treedata" on-node-clicked="changeNodeText($node)"></tree>
</div>
Directive
function treeDirectiveFactory() {
return {
restrict: 'E',
scope: {
model: '=model',
collapseIcon: '=',//IIconProvider//TODO:
expandIcon: '=',//IIconProvider//TODO:
onNodeClicked:'&',//param:$node//TODO:
isExpanded:'#'
},
templateUrl: '/_Core/DirectiveCore/Tree/TreeTemplate.html',
controller: 'TreeController',
controllerAs: 'c'
}
};
part of template
<a href={{node.link()}} class="node-link" ng-click="c.onNodeClicked(node)"
ng-class="{'margin-no-child':node['__$extension'].isLeaf(node)}">
<span ng-bind-html="node.iconProvider().htmlPath()"></span>
{{node.text()}}
</a>
when user click on node, ng-click="c.onNodeClicked(node)" will call and the node which is clicked is passed to onNodeClicked function. below is the implementation of this function in controller as c of tree directive
onNodeClicked(node: Core.INode) {//TODO:
if (this.scope["onNodeClicked"]) {
this.scope["onNodeClicked"] = ({$node:node});
}
}
I want to tell the function that you have an argument named $node and set the value of $node. then I want to change the $node text in outer controller TestController in index.html...this is the changeNodeText function in TestContoller
f($node: Core.TestNode) {
if($node !== undefined)
$node.t = "Clicked!";
}
but nothing changes, actually changeNodeText function never called. I know there is something wrong but unfortunately I can not figure it out. any help would be appreciated.
Answer for #Parud0kht
Instead of setting the function, invoke it.
onNodeClicked(node: Core.INode) {//TODO:
if (this.scope["onNodeClicked"]) {
//Do THIS
this.scope["onNodeClicked"]({$node:node});
//Not THIS
//this.scope["onNodeClicked"] = ({$node:node});
}
}
Answer for Other Readers
This example does it with components, but the same principle applies to directives.
angular.module('app.dashboard')
.component('dashboardComponent', {
templateUrl: 'app/dashboard/directives/dashboard-container.html',
controller: DashboardComponent,
controllerAs: 'DashboardCtrl',
bindings: {
onTileChange: "&"
}
})t
To communicate event data from a component to a parent controller:
Instantiate the dashboard-component with:
<dashboard-component on-tile-change="HomeCtrl.onTileChange($tile)">
</dashboard-component>
In the component controller invoke the function with locals:
this.onTileChange({$tile: tile});
The convention for injected locals is to name them with a $ prefix to differentiate them from variables on parent scope.
From the Docs:
& or &attr - provides a way to execute an expression in the context of the parent scope. If no attr name is specified then the attribute name is assumed to be the same as the local name. Given <my-component my-attr="count = count + value"> and the isolate scope definition scope: { localFn:'&myAttr' }, the isolate scope property localFn will point to a function wrapper for the count = count + value expression. Often it's desirable to pass data from the isolated scope via an expression to the parent scope. This can be done by passing a map of local variable names and values into the expression wrapper fn. For example, if the expression is increment($amount) then we can specify the amount value by calling the localFn as localFn({$amount: 22}).
-- AngularJS Comprehensive Directive API Reference
someone answered my question completely right, but unfortunately the answer was removed so quickly, I was so lucky to saw it but I could not accept it as an answer..thanks to anonymous user for his or her great answer. hope he\she will see this answer and contact me.
I should invoke the function in onNodeClicked not set it..how crazy I am !! :))) here is the answer which is working well.
onNodeClicked(node: Core.INode) {
if (this.scope["onNodeClicked"]) {
//invoking, function should be called.
this.scope["onNodeClicked"]({ $node: node });
//this is wrong and it will set an object
//this.scope["onNodeClicked"] = ({ $node: node });
}
}
this is slightly different to the other questions on stack in that, I need to call my controller's functions with parameters that exist exclusively in my directive.
directive (markup):
<div do-something="doSomething(x)"></div>
directive (js):
var directive = function () {
return {
restrict: 'EA',
templateUrl: '/angular/node-for-detail.html',
scope: {
doSomething: '&'
}
}
};
markup inside directive:
<span ng-click="doSomething('im not resolving')"></span>
function inside controller:
$scope.doSomething = function(myVar) { //myVar is null };
So the problem is, inside the directive param.abs resolved fine, but then, inside the called scope function the parameters are null! What am I doing wrong? How can I get the parameter to make it through?
You need to decide on a standard name for the parameter to the function that will be specified in the markup (in your example, you used x). Then you can create a function in the directive's isolate scope that will call the doSomething() method like so:
directive link function:
$scope.runCallback = function (param) {
$scope.doSomething({x: param});
}
Then just change your markup inside the directive to be:
<span ng-click="runCallback('im not resolving')"></span>
Now your markup call (<div do-something="doSomething(x)"></div>) and the function inside the controller will work correctly.
Try replace your markup inside directive be like this :
<span ng-click="doSomething()('im not resolving')"></span>
And directive markup :
<div do-something="doSomething"></div>
I have a form directive that uses a specified callback attribute with an isolate scope:
scope: { callback: '&' }
It sits inside an ng-repeat so the expression I pass in includes the id of the object as an argument to the callback function:
<directive ng-repeat = "item in stuff" callback = "callback(item.id)"/>
When I've finished with the directive, it calls $scope.callback() from its controller function. For most cases this is fine, and it's all I want to do, but sometimes I'd like to add another argument from inside the directive itself.
Is there an angular expression that would allow this: $scope.callback(arg2), resulting in callback being called with arguments = [item.id, arg2]?
If not, what is the neatest way to do this?
I've found that this works:
<directive
ng-repeat = "item in stuff"
callback = "callback"
callback-arg="item.id"/>
With
scope { callback: '=', callbackArg: '=' }
and the directive calling
$scope.callback.apply(null, [$scope.callbackArg].concat([arg2, arg3]) );
But I don't think it's particularly neat and it involves puting extra stuff in the isolate scope.
Is there a better way?
Plunker playground here (have the console open).
If you declare your callback as mentioned by #lex82 like
callback = "callback(item.id, arg2)"
You can call the callback method in the directive scope with object map and it would do the binding correctly. Like
scope.callback({arg2:"some value"});
without requiring for $parse. See my fiddle(console log) http://jsfiddle.net/k7czc/2/
Update: There is a small example of this in the documentation:
& or &attr - provides a way to execute an expression in the context of
the parent scope. If no attr name is specified then the attribute name
is assumed to be the same as the local name. Given and widget definition of scope: {
localFn:'&myAttr' }, then isolate scope property localFn will point to
a function wrapper for the count = count + value expression. Often
it's desirable to pass data from the isolated scope via an expression
and to the parent scope, this can be done by passing a map of local
variable names and values into the expression wrapper fn. For example,
if the expression is increment(amount) then we can specify the amount
value by calling the localFn as localFn({amount: 22}).
Nothing wrong with the other answers, but I use the following technique when passing functions in a directive attribute.
Leave off the parenthesis when including the directive in your html:
<my-directive callback="someFunction" />
Then "unwrap" the function in your directive's link or controller. here is an example:
app.directive("myDirective", function() {
return {
restrict: "E",
scope: {
callback: "&"
},
template: "<div ng-click='callback(data)'></div>", // call function this way...
link: function(scope, element, attrs) {
// unwrap the function
scope.callback = scope.callback();
scope.data = "data from somewhere";
element.bind("click",function() {
scope.$apply(function() {
callback(data); // ...or this way
});
});
}
}
}]);
The "unwrapping" step allows the function to be called using a more natural syntax. It also ensures that the directive works properly even when nested within other directives that may pass the function. If you did not do the unwrapping, then if you have a scenario like this:
<outer-directive callback="someFunction" >
<middle-directive callback="callback" >
<inner-directive callback="callback" />
</middle-directive>
</outer-directive>
Then you would end up with something like this in your inner-directive:
callback()()()(data);
Which would fail in other nesting scenarios.
I adapted this technique from an excellent article by Dan Wahlin at http://weblogs.asp.net/dwahlin/creating-custom-angularjs-directives-part-3-isolate-scope-and-function-parameters
I added the unwrapping step to make calling the function more natural and to solve for the nesting issue which I had encountered in a project.
In directive (myDirective):
...
directive.scope = {
boundFunction: '&',
model: '=',
};
...
return directive;
In directive template:
<div
data-ng-repeat="item in model"
data-ng-click='boundFunction({param: item})'>
{{item.myValue}}
</div>
In source:
<my-directive
model='myData'
bound-function='myFunction(param)'>
</my-directive>
...where myFunction is defined in the controller.
Note that param in the directive template binds neatly to param in the source, and is set to item.
To call from within the link property of a directive ("inside" of it), use a very similar approach:
...
directive.link = function(isolatedScope) {
isolatedScope.boundFunction({param: "foo"});
};
...
return directive;
Yes, there is a better way: You can use the $parse service in your directive to evaluate an expression in the context of the parent scope while binding certain identifiers in the expression to values visible only inside your directive:
$parse(attributes.callback)(scope.$parent, { arg2: yourSecondArgument });
Add this line to the link function of the directive where you can access the directive's attributes.
Your callback attribute may then be set like callback = "callback(item.id, arg2)" because arg2 is bound to yourSecondArgument by the $parse service inside the directive. Directives like ng-click let you access the click event via the $event identifier inside the expression passed to the directive by using exactly this mechanism.
Note that you do not have to make callback a member of your isolated scope with this solution.
For me following worked:
in directive declare it like this:
.directive('myDirective', function() {
return {
restrict: 'E',
replace: true,
scope: {
myFunction: '=',
},
templateUrl: 'myDirective.html'
};
})
In directive template use it in following way:
<select ng-change="myFunction(selectedAmount)">
And then when you use the directive, pass the function like this:
<data-my-directive
data-my-function="setSelectedAmount">
</data-my-directive>
You pass the function by its declaration and it is called from directive and parameters are populated.
I am trying to build generic code as much as possible.
So I'm having 2 directives, one nested inside the other while I want the nested directive to call a method on the main controller $scope.
But instead it requests the method on the parent directive, I want to know how to execute a method against the main controller scope instead of the parent directive.
Here is a sample code for my issue
My HTML should look something like this:
<div ng-controller='mainctrl'>
<div validator>
<div datepicker select-event='datepickerSelected()'/>
</div>
</div>
Javascript:
var app = angular.module("app",[]);
var mainctrl = function($scope){
$scope.datepickerSelected = function(){
//I WANT TO ACCESS THIS METHOD
}
}
app.directive("validator",function(){
return {
scope : {
//the datepicker directive requests a datepickerSelected() method on this scope
//while I want it to access the mainctrl scope
}
link: function(scope){
//some code
}
}
});
app.directive("datepicker", function(){
return{
scope: {
selectEvent: '&'
}
link: function(scope, elem){
//example code
$(elem).click(scope.selectEvent); //want this to access mainctrl instead validator directive
}
}
});
Simply remove the validator directive's scope property, thus eliminating its isolated scope. That means that validator will have the same scope that it is nested in (your controller) and datepicker will use that scope.
Another option if you want both to have isolated scopes (doesn't sound like you do) is to pass the function through to "validator's" scope.
I've searched all over the internet and cannot find a solution please help!
directive('menu',function(){
return{
link : function(scope,element,attrs){
scope.foo = function(){
alert('test!');
}
},
controller : function($scope){
$scope.foo();
}
}
});
Delay the call to foo() using $evalAsync():
controller : function($scope){
$scope.$evalAsync(function() {
$scope.foo();
console.log($scope);
});
}
fiddle
You could also use $timeout() instead of $evalAsync(). Both allow the link function to execute first.
As Ye Liu said, your controller calls your directive's compile and then link functions.
From the angular directive doc (http://docs.angularjs.org/guide/directive):
The controller is instantiated before the pre-linking phase
The controller will be within the scope of your app, and once the post-link function finishes, your directive will be a child of this scope. Consider that the link function's purpose is to bind model data to your template and set watches for bound variables, not to create a discreet 'directive object'.
If you are trying to set the foo function inside of the link function in order to access directive scope variables, take a look at directive delegate functions and bound variables in the "scope:" directive attribute. The angular directive tutorial gives a somewhat obtuse version of this as its final example ("zippy"), and Angularjs Directive Delegate not firing through intermediary handler gives an example of a delegate function you can invoke from your template itself.