I want to access or manipulate a scope's parent's parent without getting too too complicated. The controller as fashion allows for naming the parent controller as such: this.applicationCtrl.something given applicationCtrl > parent1Ctrl > child1Ctrl - siblingOfChild1Ctrl
To give you a better example, I have an applicationCtrl on the <body> tag, I have a side panel with sidePanelCtrl and the content with contentCtrl with a nested contentChildCtrl
With the controller as model, I can call or change things on the sidePanelCtrl by calling this.sidePanelCtrl, can I do the same if I just want to use $scope method?
This is specifically for the contentChildCtrl where I do not want to write $scope.$parent.$parent which still will only get me to the applicationCtrl and not the sidePanelCtrl
If you don't know the nesting level of the parent scope, or don't want to type $scope.$parent.$parent etc you can attach something like this to a service:
angular.module('app').service('inherit', function () {
var inherit = function(scope, item)
if (!scope) return;
if (scope[item]) return scope[item];
return inherit(scope.$parent, item);
}
return inherit;
}
If your namespacing isn't great then it might not help much, but if you're looking to modify, say, the sidebar contents from a grandchild scope, you could call var sidebarNav = inherit($scope, 'sidebarNav'); in the grandchild controller.
Edit - Better to put this in a service than on $rootScope as the comment below has mentioned
Edit: updated to use service
Related
I am looking for advice on how to implement a hierarchical structure in Angular, where a directive (<partition>) can call a method on a child directive's controller (<property-value>).
I have put together a detailed example here:
https://jsfiddle.net/95kjjxkh/1/
As you can see, my code contains an outer directive, <partition>, which displays one or more <property-value> directives within.
The <property-value> directive offers an editing method, editItem(), which allows the user to change the value of a single entry. (To keep my example short, I simply assign a random number here, but in my production app, a modal will appear, to query the user for a new value.)
This works fine. However, in the outer directive, <partition>, I would like to add the ability to create a new, blank <property-value> directive and then immediately call its editing method so that the user can enter an initial value. If no initial value is entered, the new item would be discarded.
I have seen examples of inner directives calling methods on enclosing directives, but not the other way around.
Is there a way to do this? Alternatively, is there a better way for me to build this kind of view?
You can always use $broadcast to talk both ways. To your parent as well as to your childrens.
In your Child controller you can do the following
app.directive('propertyValue', function() {
return {
require : '^partition'
restrict: 'E',
scope: {
item: '='
},
with this you will get the parent controller in child directive's link function like this
link:function(scope,element,attrs,partitionCtrl){
partitionCtrl.getChildCtrl(element)
}
in partition controller create getChildCtrl function and with that call "propertyvalue" controller function
controller: function ($scope, ItemFactory) {
// your code
var propValueCtrl =undefined;
this.getChildCtrl =function(elem)
{
propValueCtrl = elem.controller();
}
this.callChildFunction = function()
{
propValueCtrl.Edit();// whatever is the name of function
}
call this function when needed in property link function.
Hope this helps.
I have an Angular app where I'm using ui-grid. I want to have a custom action on a cell of the grid that calls a method from my app. So basically, this means calling a method that's somewhere up in the parent hierarchy, from a directive.
This would be achieved by calling something like: $scope.$parent.$parent.$parent.$parent.foo(). But that doesn't seem too nice.
One option would be to create a recursive function that goes up the ancestry of the $scope. That's nicer, but still seems a bit weird.
Also... Is it good practice to try to achieve something like this?
You're correct that $parent.$parent.$parent is definitely not a good practice.
If the method you're calling is another directive, you can require that directive in your child directive and then, the parentDirective's controller function will be injected as the fourth parameter to your link function:
In your DDO:
return {
require : '^parentDirective',
restrict : 'E',
link : function (scope, elem, attrs, parentDirectiveController) {}
}
If what you're trying to call is on a factory/service, you can inject that factory/service into your directive, although this sometimes is a code smell, depending on what you're trying to inject.
Finally, another way to do it is to use event propagation. From your directive, you can use $scope.$emit to send information up to parent controllers:
From the directive:
$scope.$emit('directiveDidStuff', {
data : 'blah'
});
In the parent controller:
$scope.$on('directiveDidStuff', function (evt, params) {
this.data = params.data; // equals blah
});
You can achieve the same by using "&" through one of the scope variable in directive.Like this, you can bind your event to the controller method and from the method, you could do your desired things or if the original business logic which you wants to achieve on onClick of the grid is used across many modules than you can bisect it in service and make it reusable and call the service from the event method. Let me know if you do have any doubts with the approach.
Key Code of example:
Html
<my-component attribute-foo="{{foo}}" binding-foo="foo" isolated-expression- foo="updateFoo(newFoo)" >
Directive
var myModule = angular.module('myModule', [])
.directive('myComponent', function () {
return {
restrict:'E',
scope:{
/* NOTE: Normally I would set my attributes and bindings
to be the same name but I wanted to delineate between
parent and isolated scope. */
isolatedAttributeFoo:'#attributeFoo',
isolatedBindingFoo:'=bindingFoo',
isolatedExpressionFoo:'&'
}
};
})
I have a directive(parent-directive) containing a slider(mySlider), that on stop event, call an angular $resource service with 2 params and the service return an object.
Directives structure:
<parent-directive>
<div ui-slider="slider.options" ng-model="mySlider" id="my-slider">
<span child-directive-one></span>
<span child-directive-two></span>
<span child-directive-three></span>
<div>
<span child-directive-four></child-directive-four>
</div>
</parent-directive
Whenever the user drag the slider, the service is called with different params and retieve new result, based on it I need to update the child directives.
I have in mind three ways:
using ng-model for all child elements instead directives, binding them on the scope of a controller in parent-directive;
the second one, that I don't know how to do it, is to create a controller in the parent-directive, that send and receive data from the service and share it to child-directives in order to update them.
the last one is to to create a state variable in the service and update it using a controller like to point 1.(see it above) and use a $watch to supervise the variable state and when it's changed then update the child-directives.
How should I proceed?
Please have a look here to see a brief code:
http://jsfiddle.net/v5xL0dg9/2/
Thanks!
ngModel is intended for two way binding, i.e. controls that allow the user to interfere with the value. From the description, it seems they are display-only components. So I would advise against using the ngModel.
Normally child directives require their parent. This allows them to call methods on the parent controller. What you need is the opposite: the parent controller needs to call methods on the children. It can be done: the children call a registerChild() method, and the parent iterates all registered children when it needs to call them. I find this implementation cumbersome.
Services are globals/singletons. I would vote against tying the service implementation to the UI needs.
My advice looks like your implementation of option 3, but with the parent controller holding the data:
1) Place the data you want to share with the child directives in a member variable of the parent controller:
myApp.directive('parentDirective', ['myService', function(myService){
...
controller: function($scope) {
...
this.sharedThing = ...;
}
}]);
The sharedThing can be updated when the service returns new data, or any other time it is necessary.
2) Have the children require the parent (just like your option 2), and watch this property:
myApp.directive('childDirectiveOne', function() {
return {
...
require: 'parentDirective',
link: function(scope, elem, attrs, parentDirective) {
scope.$watch(
function() {
return parentDirective.sharedThing;
},
function(newval) {
// do something with the new value; most probably
// you want to place it in the scope
}
});
}
};
});
Depending on the nature of the data, a deep watch may be required.
Consider two nested directives with isolate scopes:
<dctv1>
<dctv2></dctv2>
<dctv1>
If I want dctv2 to talk to dctv1 I have may options:
I may require the controller of dctv1 in the definition of dctv2 using the require:'^dctv1'
I may call an expression on the parent scope with the wrapper <dctv2 callParent="hello()"></dctv2> and scope:{callParent:'&'}
I can also use $scope.$emit in dctv2 but then all parent scopes will hear the message.
Now I want dctv1 to talk to dctv2.
The only way I may accomplish this is to use $scope.$broadcast, but then all children will hear.
By talk to here i mean call a function or similar. Don't want to set up watches clogging the digestloop.
How can I make dctv1 notify dctv2 in the best way, making them loose-coupled? I should just be able to remove dctv2 without errors.
Take a look at AngularJS NgModelController for some ideas.
Each <dctv2> directive would require <dvtv1> to have it's controller injected. You can then add objects or callbacks to properties of that controller, and remove them when <dctv2> is destroyed.
<dvtv1> would not talk directly to children, but would trigger callbacks bound to it's properties.
For example;
NgModelController has $parsers and $formatters that are an array of function callbacks. You push your own functions into the array to extend that controllers behavior.
When NgModelController performs input validation it's basically talking to other directives via these properties.
I would suggest using angular services. That way you can decouple your behavior into one or more services.
Take a look at this also : AngularJS : How to watch service variables?
One way is to make a Service/Factory that will communicate with the controllers that you want.
For example, here's a getter/setter Factory
.factory('factoryName', function () {
var something = "Hello";
return {
get: function () {
return something;
},
set: function (keyword) {
something = keyword;
return something ;
}
};
}])
And then in your controllers:
.controller('controllerOne', ['factoryName', function (factoryName) {
$scope.test = factoryName.get();
}]);
.controller('controllerTwo', ['factoryName', function (factoryName) {
$scope.test = factoryName.get();
$scope.clickThis = function (keyword) {
factoryName.set(keyword);
};
}]);
I suggest reading up on this : Can one controller call another?
You can manage it using an id for each child that have to be passed to the parent; the parent will broadcast back the event using that id: the child will do the action only if the id passed from the parent is the his own.
Bye
Within a directive definition, there's an API for accessing $element and $attrs, so you can refer back to the element from which the directive was called. How would I access $element and $attrs when calling a custom function using a standard directive like ng-class?
EDIT: I understand that this is not an idiomatic approach. This question is applicable to rapid prototypes, which is a great use for many of Angular's features. Just not the ones that are all about sustainability, separation of concerns, etc. My primary concern is velocity. Thus, being able to bang something out quickly with the built-in directives and a quick controller method can, in fact, be a virtue, and can win the opportunity to do a fuller and more proper implementation down the road...
In this case, I'm just adding a contextual .active class to a nav element, based on the value of $location.path(), as per this post and this one. However, in those examples you need to explicitly and redundantly pass a copy of the contents of the href attribute as an argument to the getClass() function you're calling from ng-class. But isn't there a way to programmatically access the href attribute from within getClass() and avoid redundantly passing identical content as an arg?
For example, a controller with a getClass() function the way I'd imagine it could work:
function navCtrl($scope, $routeParams) {
$scope.getClass = function($element, $attrs) {
if ($location.path().substr(0, path.length) == $attrs.href) {
return "active"
} else {
return ""
}
}
}
Which you could then call simply and elegantly with:
<a ng-class="getClass()" href="/tasks">Tasks</a>
rather than:
<a ng-class="getClass('/tasks')" href="/tasks">Tasks</a>
(I recognize another option is to create a custom directive that does this, but for now I'd just like to figure out if it's possible to access $attrs and/or $element from within a controller function that's been called by a directive. Thanks!)
You actually can do this... BUT YOU SHOULD NOT DO THIS. lol...
Here's how to do what you're asking...
In your markup, pass $event into your function.
<a ng-click="test($event)" href="whatever">Click Me</a>
Then in your controller, get the target element of the event:
$scope.test = function($event) {
alert($event.target.href);
};
Now here is why you probably shouldn't do this:
If you reference the DOM, or manipulate the DOM in your controller, you're endangering dependency injection and also the separation of concerns from within the Angular structure. Sure you could still inject $event as a dependency if you were testing your function, but depending on what you're doing inside of that function, you might still have ruined your DI, and you're trying to make a controller do a directive's work (which is to try to keep your controller from being tightly-coupled to your markup)
That said, if ALL your doing is just getting a value, it's probably fine, but you're still coupling your controller to your markup to some degree. If you're doing anything else with that DOM element, you're off the reservation.
I don't think you can do that. The angular philosophy is to avoid accessing the DOM directly from your controller. You have already identified your two options for doing this in Angular:
pass in the href as a param i.e.. getClass('/tasks')
or, write a custom directive
Alternatively, if the class is purely presentational and doesn't affect how your application runs then you could ignore angular and use a quick and dirty jQuery function to do the job for you.
The lack of direct interaction with the DOM can be a bit strange at first but it's a godsend in the long term as your codebase grows, gets more complicated and needs more tests.
Here's a completely different answer: you don't need a Angular to change styling based on href. You can use CSS selectors for that.
In your styles:
a[href="/something"] {
background-color: red;
}
That in combination with anything you might be doing with ng-class should be everything you need.