Passing element attributes from parent to child with Angular JS 1.3 - javascript

I have a problem with Angular JS. I have two directives.
angular.module('myModule', [])
.directive('myFirstDirective', function(){
return {
link: function (scope, elem, attr) {
var myAttributeToPass = attr.myFirstDirective;
scope.myAttr = myAttributeToPass;
},
controller: 'MyFirstController'
}
})
.controller('MyFirstController', function($scope){
this.returnTheParameter = function(){
return $scope.myAttr;
}
})
.directive('mySecondDirective', function(){
return {
require : ['ngModel', '^myFirstDirective'],
link : function($scope, element, attrs, ctrls) {
var ngModel = ctrls[0];
var myFirstCtrl = ctrls[1];
var theParamOfFirst = myFirstCtrl.returnTheParameter();
}
}
});
I init my first value with a string :
<div my-first-directive="foobar"> (... => my second directive is inside) </div>
My problem is in the life cycle, the returned value is always undefined because the controller is called before the link. When i do an isolated scope, with :
scope: {
"myProp": "#myFirstDirective"
}
That's works but i don't want to isolate the scope...
Any ideas ?
Thanks a lot !

The problem lies in the order in which the operations are taking place.
It sounds like you will need to compile things in a specific order. In which case I would like to refer you to this post: How to execute parent directive before child directive? so I don't borrow the full thunder of another person's explanation.
Ultimately you would want to do something along the lines of:
return {
compile: function(){
return{
pre:function (scope, elem, attr) {
var myAttributeToPass = attr.myFirstDirective;
scope.myAttr = myAttributeToPass;
},
post: angular.noop
};
},
controller: 'MyFirstController'
};
for your first directive and for the second directive:
return {
require : ['^myFirstDirective'],
compile: function(tElement, tAttrs, transclude){
return{
pre: angular.noop,
post: function($scope, element, attrs, ctrls) {
var ngModel = attrs.ngModel;
var theParamOfFirst = ctrls[0].returnTheParameter();
}
};
}
};
The angular.noop above is just an empty method returning nothing.
For a working example feel free to browse the plunk I threw together (http://plnkr.co/edit/pe07vQ1BtTc043gFZslD?p=preview).

Related

What is the scope of ngModel directive in AngularJS?

I think that ngModel directive should not create new scope as it needs to make changes in the variables of parent scope.
Please correct me if i am wrong .
And also looking at the source of ngModel directive scope is not defined so it should not create a new scope for directive.
var ngModelDirective = ['$rootScope', function($rootScope) {
return {
restrict: 'A',
require: ['ngModel', '^?form', '^?ngModelOptions'],
controller: NgModelController,
// Prelink needs to run before any input directive
// so that we can set the NgModelOptions in NgModelController
// before anyone else uses it.
priority: 1,
compile: function ngModelCompile(element) {
// Setup initial state of the control
element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);
return {
pre: function ngModelPreLink(scope, element, attr, ctrls) {
var modelCtrl = ctrls[0],
formCtrl = ctrls[1] || modelCtrl.$$parentForm;
modelCtrl.$$setOptions(ctrls[2] && ctrls[2].$options);
// notify others, especially parent forms
formCtrl.$addControl(modelCtrl);
attr.$observe('name', function(newValue) {
if (modelCtrl.$name !== newValue) {
modelCtrl.$$parentForm.$$renameControl(modelCtrl, newValue);
}
});
scope.$on('$destroy', function() {
modelCtrl.$$parentForm.$removeControl(modelCtrl);
});
},
post: function ngModelPostLink(scope, element, attr, ctrls) {
var modelCtrl = ctrls[0];
if (modelCtrl.$options && modelCtrl.$options.updateOn) {
element.on(modelCtrl.$options.updateOn, function(ev) {
modelCtrl.$$debounceViewValueCommit(ev && ev.type);
});
}
element.on('blur', function() {
if (modelCtrl.$touched) return;
if ($rootScope.$$phase) {
scope.$evalAsync(modelCtrl.$setTouched);
} else {
scope.$apply(modelCtrl.$setTouched);
}
});
}
};
}
};
}];
Also I don't understand why ngModel directive requires ngModel itself.
require: ['ngModel', '^?form', '^?ngModelOptions']
Can't it be ignored and written like
require: ['^?form', '^?ngModelOptions']
If not then please explain why ?
ngModel doesn't create an isolated scope. The reason ngModel is listed in the require array is so that its controller (NgModelController) will be injected into the link function. Notice the ctrls argument that is passed into the ngModelPostLink function. Because ngModel is listed in the array, ctrls[0] will be an instance of the NgModelController. ctrls[1] is the form controller, etc.

Custom validators with AngularJs

I'm writing my own custom AngularJs validators which look like this:
.directive('float', function ($log) {
return {
restrict: 'A',
require: 'ngModel',
scope: {float: '='},
link: function ($scope, ele, attrs, ctrl) {
var settings = $scope.float || {};
ctrl.$validators.float = function(value) {
var valid = isTheInputValidFunction( settings );
ctrl.$setValidity('float', valid);
return valid;
};
}
};
});
I'm using the validators like so:
<input type="text"ng-model="someVar" name="preis" float="{precision: 5, scale: 2}">
However, as soon as I attach multiple validators, I get the following error:
Multiple directives [...] asking for new/isolated scope
This is, because all my validators get a settings-object which has to be passed into the scope scope: {float: '='}.
I know that I can use var settings = JSON.parse(attrs.float); in the directives, but it doesn't look right.
So my question is:
How do you correctly implement custom validators in AngularJs?
It really depends on whether you expect the settings to change.
If you think it will be constant, like in the example you've shown, then simply parsing once the value will be enough. The appropriate service to use in such a case is $parse:
link: function ($scope, ele, attrs, ctrl) {
var settings = $parse(attrs.float)($scope);
// …
}
If you think it may be used with a variable, you should watch its content:
link: function ($scope, ele, attrs, ctrl) {
var settings = undefined;
$scope.$watch(attrs.float, function (newSettings) {
settings = newSettings;
});
// …
}
Perhaps it is because you are calling $setValidity. I beleive the whole point of the $validators pipeline was to do it for you. Just return a boolean.
ctrl.$validators.float = function(value) {
return isTheInputValidFunction( settings );
};

Angular directive link function never runs

I followed the tutorial of ng-bbok, and at the directive definition an empty compile function is inserted and then the link function. With this the code in the link function never got executed. Finally i figured out that is because the empty compile function, when i deleted it magically the link got executed. Why is it happening like this? Im using Angular 1.3
{
compile: function() {},
link: function($scope, element, attributes) {
var size = attributes.gravatarSize || 80;
var hash = md5.digest_s($scope.email.from[0]);
$scope.gravatarImage = url + hash + '?size=' + size;
}
}
You can't define both compile property and link. If you want to use the compile function you can either return the link function:
compile: function() {
return function($scope, element, attributes) {
var size = attributes.gravatarSize || 80;
var hash = md5.digest_s($scope.email.from[0]);
$scope.gravatarImage = url + hash + '?size=' + size;
}
}
Or define both pre and post (link) functions:
compile: function compile(tElement, tAttrs, transclude) {
return {
pre: function preLink(scope, iElement, iAttrs, controller) { ... },
post: function postLink(scope, iElement, iAttrs, controller) { ... }
}
}
Check the documentation
It's happening by design. To quote the $compile docs:
link
This property is used only if the compile property is not defined.

passing defined object to another custom directive angularjs

so I have this custom directives that you could see below.
myApp.directive('myDirective', function (testService) {
return {
restrict:'EA',
link:function (scope, element, attr) {
//defined the object
var object = new object();
testService.setObject(object);
}
}
});
myApp.directive('mySecondDirective', function (testService) {
return {
restrict:'EA',
link:function (scope, element, attr) {
//call the variable from previous custom directive
console.log(testService.getobject()); -> always return undefined
}
}
});
and this is the html structure where I used the directives above.
<my-directive></my-directive>
<my-second-directive></my-second-directive>
there I want to retreive the object that contains new object() from previous custom directive, but it always return an undefined I wonder how could I do this without using require nor isolated scope as well.. could you guys help me ?
UPDATE
I create a service to provide the facility to set and retreive the object and apparently it returned undefined because I set the custom direcitve this way
<my-second-directive></my-second-directive>
<my-directive></my-directive>
and this is the service
define(
['services/services'],
function(services)
{
'use strict';
services.factory('testService', [function() {
var me = this;
var testObject = '';
return {
setObject: function(object) {
me.testObject = object;
},
getObject: function() {
return me.testObject;
}
}
}
]);
}
);
the thing is that I actually set the html markup like I already mentioned above which is
<my-second-directive></my-second-directive>
<my-directive></my-directive>
so could you give me some advice on how should I do this ?
note* that the passing object actually worked I prefer using services because it will easy to mantain latter. The question is how do I make the object accessible from another directive even though the initiate install of the object (set the object) in the directive that I defined at the html markup, as the last position of the html it self ?
UPDATE this is the PLUNKER that I've been made for you to understand the question it self
You could achieve this by firing a custom event and then listening for it in the second directive. Here's an updated plunker: http://plnkr.co/edit/512gi6mfepyc04JKfiep?p=info
Broadcast the event from the first directive:
app.directive('myDirective', function(testService) {
return {
restrict: 'EA',
link: function(scope, elm, attr) {
var object = {};
testService.setObject(object);
console.log('setting object');
scope.$broadcast('objectSet');
}
}
});
... and then listen for it on the second:
app.directive('mySecondDirective', function(testService) {
return {
restrict: 'EA',
link: function(scope, elm, attr) {
scope.$on('objectSet', function(){
console.log('retrieving object', testService.getObject());
})
}
}
});
You could also pass data along with the event, if you wanted to emit a specific piece of data to be picked up by the second directive.
1). Scope. Since you don't want to use controllers and isolated scope, then you can simply set this object as scope property.
myApp.directive('myDirective', function() {
return {
restrict: 'EA',
link: function(scope, element, attr) {
var object = {};
object.test = 21;
// set object as scope property
scope.object = object;
}
}
});
myApp.directive('mySecondDirective', function() {
return {
priority: 1, // priority is important here
restrict: 'EA',
link: function(scope, element, attr) {
console.log('Retrieve: ', scope.object);
}
}
});
Just make sure you are also defining priority on the second directive (only if both directive a applied to the same element) to make sure it's evaluated in proper turn (should be bigger then the one of myDirective, if omitted it's 0).
2). Service. Another simple solution is to use service. You can inject custom service into both directives and use it storage for you shared object.
Expanding from what #gmartellino said.
Anything that you wanted to do after listening to the event in second directive, can have a callBack method and use it.
app.directive('mySecondDirective', function(testService) {
return {
restrict: 'EA',
link: function(scope, elm, attr) {
// what if I created like this ?
// define the test variable
var test;
scope.$on('objectSet', function(){
//set the variable
test = testService.getObject();
console.log('retrieving object : ', testService.getObject());
//Anything that you wanted to do
//after listening to the event
//Write a callBack method and call it
codeToExecuteAsCallBack();
})
//then use this method to make a call back from the event
//and outside the event too.
var codeToExecuteAsCallBack = function(){
console.log(test);
}
codeToExecuteAsCallBack();
}
}
});
Updated plnkr link

Call directive API method from 'parent' controller in AngularJS

I have a situation where I want to create custom component, which should be reusable and provide public API to change it's state. I am trying to achieve this by building component using directive and controller.
What I desire to do is simply:
customComponent.apiMethod1( Math.floor( Math.random() * 2 ) );
Here is JSFiddle which should explain my case: http://jsfiddle.net/7d7ad/4/
On line 9 ( when user clicks a button ), I want to call line 22 method ( custom component public API method ). Is there anyway to achieve this?
You are looking for Providers. There are three different types: Factories, Services, and Providers. Each is a bit different you can take a look at this summary.
Providers can allow you to share common methods, functions and data between different areas of your application without duplicating code.
Short example - Fiddle
html
<div ng-app="myApp" ng-controller="testController">
<button ng-click="ClickMe()">Random</button>
{{display.value}}
</div>
javascript
angular.module('myApp', [])
.controller('testController', ['$scope','myService', function($scope, myService) {
$scope.display =new myService();
$scope.ClickMe = function() {
$scope.display.apiMethod1();
};
}])
.factory('myService', function() {
function factory() {
this.value = "Hello World";
this.apiMethod1 = function() {
this.value = Math.floor( Math.random() * 2 );
};
}
return factory;
});
You can, in addition to a service, use a parent directive with a controller.
Here is an example of how this might work (service example at the bottom):
app.directive('parentDir', function() {
return {
controller: function($scope, $element) {
var childFuns = [];
this.registerFun = function(func) {
childFuns.push(func);
}
//we will call this using ng-click
$scope.onClick = function(){
childFuns.forEach(function(func){
func.call(null,5)
});
}
}
}
})
And in the child directive:
app.directive('customcomp', function() {
return {
restrict: 'E',
scope: {},
require: '^parentDir', //we "require" the parent directive's controller,
//which makes angular send it as the fourth
//argument to the linking function.
template: '<h2>{{_currentNumber}}</h2>',
link: function(scope, elm, attrs, ctrl) {
scope._currentNumber = 0;
scope.apiMethod1 = function(val) {
scope._currentNumber = val;
};
//call the parent controller's registring function with the function
ctrl.registerFun(scope.apiMethod1);
}
}
});
Each child directive would "register" a function, and those functions can be stored and called from the parent directive in any way you want.
Note that you should use ng-click for events with angular.
FIDDLE
And here is how it might look with a service:
app.service('funcs', function(){
var funcs = [];
this.register = function(func){ funcs.push(func)};
this.call = function(){
funcs.forEach(function(func){
func.call(null,5);
})
}
})
FIDDLE

Categories

Resources