Passing method through a directive to a parent directive - javascript

edit: Modified the code as per stevuu's suggestion as well as added a plunkr to here
I'm currently attempting to have a child directive call a method(resolve) through another directive all the way up to a parent directive but I'm having difficulties identifying the problem with my approach.
The problem right now seems to be that although resolve() does get called as expected on click, selected remains undefined.
the html:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Angular: directive using & - jsFiddle demo</title>
<script type='text/javascript' src='//code.jquery.com/jquery-1.9.1.js'></script>
<link rel="stylesheet" type="text/css" href="/css/normalize.css">
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<script type='text/javascript' src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<style type='text/css'>
</style>
</head>
<body ng-app="myApp">
<div grand-parent>
<span>selected: {{text}}</span>
<div parent resolve="resolve"></div>
</div>
</body>
</html>
And the js:
var myApp = angular.module('myApp',[]);
myApp.directive('grandParent', function() {
return {
scope:{
resolve: "&"
},
link: function($scope, $element) {
$scope.resolve = function(selected){
$scope.text = selected
}
}
};
});
myApp.directive('parent', function(){
return{
scope: {
resolve: "&"
},
template: "<div child resolve='resolve'></div>"
};
});
myApp.directive('child', function() {
return {
scope: {
resolve: "&"
},
template: "<div>Click me!</div>",
link: function($scope, $element) {
$element.on("click", function(){
$scope.$apply(function(){
$scope.resolve({selected: "Yahoo!!"});
});
});
}
};
});

resolve: "&" is a mapping. So here:
myApp.directive('grandParent', function() {
return {
scope:{
resolve: "&"
},
link: function($scope, $element) {
$scope.resolve = function(selected){
$scope.text = selected
}
}
};
});
you are trying to map "resolve" to ... nothing, because "grandParent" doesn't have any attr named "resolve".
If you want to share some staff betweens directives you should do something like that:
view
<div data-grand-parent resolve="resolved()">
<div data-parent ></div>
</div>
Directives
var app = angular.module('test');
app.directive('grandParent', function() {
return {
scope : {
resolve : "&" // in view we defined resolve attr
// with "resolve()" value, so now resolve=resolved()
// in grandParent scope too.
},
controller: function($scope){
this.getResolve = function(){
return $scope.resolve;
};
}
};
});
app.directive('parent', function() {
return {
require: "^grandParent",
link: function(scope, element, attr, grandParentCtrl){
grandParentCtrl.getResolve()();
},
template : ""
};
});
controller
angular.module('desktop')
.controller('MainCtrl', function ($scope, mocks) {
$scope.resolved = function(){
console.log("calling $scope.resolved() ...");
};
});
output
calling $scope.resolved() ...
So, how does it work?
We defined resolved function in our controller, then we sign this function to attr "resolve" in grandParent directive. Thx to resolve : "&" we could mapped that resolved() function to "resolve" property in grandParent scope. At the end we inject grandParent to other directives. That's all.
I recommend you to read angularJs by Brad Green, Shyam Seshadri. it's not the best book but could be worse and it's free. You can find very good tutorial too on http://www.egghead.io/
ps. Sorry for my english ;/

Related

Access to scope in angular directive with two data bindigs

good morning i have a small problem i have directive:
return {
restrict:'E',
scope: {
user: "="
},
template: '<b>{{userLogin}}</b>',
link:function(scope,elem,attrs){
},
controller: function ($scope) {
console.log($scope.user)//always undefindet
$scope.userLogin = $scope.user;
},
};
and i want to show my parameter "user" with scope in template i must use controller because i need download some data from server
I think problem is somewhere here(in directive):
scope: {
user: "=" //when i have this response "undefined"
user: "#" //when i have this response not show id only text
},
my HTML
<get-user-login user="{{post.user_id}}"></get-user-login>
i always getting: empty value or undefined in console.
How to fix that.
When using # you have to use interpolation as:
<get-user-login user="{{post.user_id}}"></get-user-login>
Note # is ONLY for text values
WHEREAS
When using = you do not need interpolation
<get-user-login user="post.user_id"></get-user-login>
Note = is only for passing objects (two way binded)
I built this demo for you and it works just fine :
<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body ng-controller="ctrl">
<get-user-login user="post.user_id"></get-user-login >
<script>
angular.module("app",[])
angular.module("app").
controller("ctrl",function($scope){
$scope.post = {user_id:565};
}).
directive('getUserLogin', function() {
return {
restrict:'E',
scope: {
user: "="
},
template: '<b>{{userLogin}}</b>',
link:function(scope,elem,attrs){
},
controller: function ($scope) {
console.log($scope.user)//always undefindet
$scope.userLogin = $scope.user;
},
};
});
</script>
</body>
</html>
Are you sure that you're giving correct value to directive? Because in getPost you're binding it to $scope.onePost, so maybe correct way is:
<get-user-login user="{{onePost.user_id}}"></get-user-login>

How to use angular listener when using ng-repeat?

When I click a button, the controller will get data from some $http service callback function and will $broadcast it on $scope. Then, in the directive, I have a listener to get the data and do some logic. But, when I am using ng-repeat on button for several formats, the listener will get fired for all ng-repeat items when I click on each button. How can I make the listener to get fired only for the clicked button? Please see the sample code below.
var app = angular.module('demoApp', []);
app.controller('MyCtrl', function($scope) {
var myCtrl = this;
myCtrl.getFile = function(){
var response = 'some data';
$scope.$broadcast('downloadFile', {'response': response});
}
});
app.directive('fileDownload', function(){
return {
restrict: 'A',
link: function(scope, elem, attrs){
var cancelEvent = scope.$on('downloadFile', function(event, args){
console.log('called', args);
});
scope.$on('$destroy', function(){
cancelEvent();
});
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demoApp">
<div ng-controller="MyCtrl as myCtrl">
<button ng-repeat="format in ['TXT','PDF','CSV']" ng-click="myCtrl.getFile()" file-download>{{ format }}</button>
</div>
</div>
In this sample you can figure out how can create directive using scope, i create a sample to get all formats get all lists, get checked list, get download format, on directive.
About your codes, actually response is true, because when we use some functions like [$broadcast] or ... on app run all data already sets in our scopes. but remember in this case you don't need to use $broadcast that because our actions are in-time and we can get them when we click on a function.
hope helps you my friend
var app = angular.module('app', []);
app.controller('ctrl', function ($scope) {
var self = this;
self.lists = [
{ name: "A"},
{ name: "B"},
{ name: "C"},
{ name: "D"}
];
self.getFile = function () {
console.log('controller', "done");
}
});
app.directive('fileDownload', function ($filter) {
return {
restrict: 'A',
scope: {
fileDownload: "=",
list: "="
},
link: function (scope, elem) {
elem.on("click", function () {
var filter = $filter("filter")(scope.list, { checked: true });
console.log('from directive, all list', scope.list);
console.log('from directive, checked list', filter);
console.log('from directive, download format', scope.fileDownload);
});
}
}
});
<!DOCTYPE html>
<html ng-app="app" ng-controller="ctrl as self">
<head>
<title></title>
</head>
<body>
<small>list</small>
<ul>
<li ng-repeat="list in self.lists">
<input type="checkbox" ng-model="list.checked"/>
{{list.name}}
</li>
</ul>
<small>download format</small>
<button ng-repeat="format in ['TXT','PDF','CSV']" ng-click="self.getFile()" list="self.lists" file-download="format">{{ format }}</button>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</body>
</html>
I think it will help you
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demoApp">
<div ng-controller="MyCtrl as myCtrl">
<span ng-repeat="format in ['TXT','PDF','CSV']">
<span get-file="myCtrl.getFile({data: data})" file-download title="format"></span>
</span>
</div>
</div>
</body>
<script type="text/javascript">
var app = angular.module('demoApp', []);
app.controller('MyCtrl', function($scope) {
var myCtrl = this;
myCtrl.getFile = function(data) {
var response = 'some data';
console.log(response);
console.log(data);
// $scope.$broadcast('downloadFile', {'response': response});
}
});
app.directive('fileDownload', function() {
return {
restrict: 'A',
template: "<button ng-click='callFn()'>{{title}}</button>",
scope: {
title: '=',
getFile: '&'
},
link: function(scope, elem, attrs, ctrl) {
scope.callFn = function(){
scope.getFile({data: scope.title});
}
// var cancelEvent = scope.$on('downloadFile', function(event, args) {
// console.log('called', args);
// });
// scope.$on('$destroy', function() {
// cancelEvent();
// });
}
}
});
</script>
</html>

getting data in child directive from parent directive in Angular JS

I have a parent directive in which its controller makes a call through a service to get some data.
sharedService.getData(options).then(function(data){
$scope.data = data;
});
Now i need this data in my child controller.
What i have already tried are the ff:
1) Through $timeout i get the data after sometime but it doesn't seem a good solution impacting performance
2) watchCollection() - i watched if newValue !== oldValue
problem being the data is huge so it takes a toll of performance
Now the issue i'm getting is the child directive gets executed after parent BUT before the data comes back from the service and i'm not able to get that data in my child directive via $scope.data.
Is there any solution to get data from parent directive to child directive when i have to wait for data to come in parent?
You can include your parent directive controller in your child directive by using require.
angular.module('myApp', [])
.directive('dirParent', function() {
return {
restrict: 'E',
scope: {},
controller: ['$scope', function($scope) {
}],
};
})
.directive('dirChild', function() {
return {
require: '^dirParent', // include directive controller
restrict: 'E',
scope: {
},
link: function(scope, element, attrs, paretCtrl) {
var data = paretCtrl.getMyData();
}
};
})
It's always a best to use service for communication and and business logic. Here is an example. Please check. This might solve your problem.
// Code goes here
angular.module('app', [])
.factory('messageService', function() {
return {
message: null
}
})
.directive('parentDir', function() {
return {
scope: {}, //isolate
template: '<input type="text" ng-model="PDirInput"/><button ng-click="send()">Send</button>',
controller: function($scope, messageService) {
$scope.send = function() {
messageService.message = $scope.PDirInput;
}
}
}
})
.directive('childDir', function() {
return {
scope: {}, //isolate
template: '<code>{{CDirInput.message}}</code>',
controller: function($scope, messageService) {
$scope.CDirInput = messageService;
}
}
})
<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="angular.js#*" data-semver="2.0.0-alpha.31" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<HR/>Parent Directive
<parent-dir></parent-dir>
<br/>
<HR/>Child Directive
<child-dir></child-dir>
<HR/>
</body>
</html>

Not able to access scope from directive of controller in AngularJS

I am new to AngularJS, I have used service to get data from back end and received it in controller,now I have to parse those values and dynamically create elements in directive,when I am trying to do so I am getting undefined for values in controller.
app.js:
var app = angular.module('childAid', ["myDirectives"]);
app.controller('headerController', function($scope, headerFactory) {
debugger
headerFactory.getAllChallenges()
.then(function(data) {
$scope.challengeslist = data.header;
});
});
directiveExample.js
var myDirectives = angular.module('myDirectives', []);
myDirectives.directive('headerPicker', function() {
return {
restrict: 'AE',
templateUrl: 'component/views/header.html',
link: function($scope, element, attributes) {
console.log('linking foo ' + $scope.challengeslist);
}
};
});
serviceExample.js:
(function() {
angular .module('childAid').factory('headerFactory', headerFactory);
function headerFactory($http) {
function getAllChallenges() {
debugger
return $http
.get('resources/stubs/details_tree.json')
.then(complete)
.catch(failed);
}
// helper function to handle the resolved promise
function complete(response) {
debugger
return response.data;
}
// helper function to handle the rejected promise
function failed(error) {
console.error(error.statusText);
}
return {
getAllChallenges: getAllChallenges
};
}
headerFactory.$inject = ['$http']; })();
index.html:
<div ng-app="childAid" ng-controller="headerController">
<div class="container">
<h2>Displaying Header</h2>
<header-picker></header-picker>
</div>
I don't know where I am doing wrong,Kindly help I am new to AngularJS.
Have you tried using an isolate scope on your directive. It might work out easier for you if you tried something like this..
DEMO
Obviously I don't have access to your api so I've mocked it using a public dummy api, so you will have to modify this to work with your own server.
The important bits are..
return {
restrict: 'AE',
templateUrl: 'header.html',
scope: {
'challengesList' : '='
}
};
.. in your directive, and
<header-picker challenges-list='challengesList'></header-picker>
.. in your html.
Here's the whole thing for reference. Hope you find it useful. Sorry if you've already tried this.
app.js
var app = angular.module('childAid', ["myDirectives"]);
app.controller('headerController', function($scope, headerFactory) {
debugger
headerFactory.getAllChallenges()
.then(function(response) {
$scope.data = response;
// $scope.challengesList = data.header;
// dummy response has a data.title property,
$scope.challengesList = response.data.title;
});
});
angular
.module('childAid')
.factory('headerFactory', headerFactory);
headerFactory.$inject = ['$http'];
function headerFactory($http) {
function getAllChallenges() {
debugger
// var url = 'resources/stubs/details_tree.json';
// dummy api for demo purposes, obviously delete this
// and uncomment your own url for your own app
var url = 'http://jsonplaceholder.typicode.com/posts/1';
return $http
.get(url)
.catch(failed);
}
// helper function to handle the rejected promise
function failed(error) {
console.error(error.statusText);
}
return {
getAllChallenges: getAllChallenges
};
}
var myDirectives = angular.module('myDirectives', []);
myDirectives.directive('headerPicker', function() {
return {
restrict: 'AE',
templateUrl: 'header.html',
scope: {
'challengesList' : '='
}
};
});
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.2/angular.js" data-semver="1.4.2"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-app="childAid" ng-controller="headerController">
<pre>{{data}}</pre>
<div class="container">
<h2>Displaying Header</h2>
<header-picker challenges-list='challengesList'></header-picker>
</div>
</div>
</body>
</html>
header.html
<p>challengeslist = {{challengesList}}</p>

Angular directive that requires another directive that uses an Attribute defined controller

I'm learning angular and when I was studying custom directives I got stuck in a situation that I don't know how to solve. Here are my custom direcives:
/**
* Created by Lucas on 11/06/2015.
*/
'use strict'
eventsApp
.directive('greeting',function() {
return {
restrict: 'E',
replace: true,
template: "<button class='btn' ng-click='sayHello()'>Say Hello</button>",
controller: function GreetingController($scope) {
var greetings = ['hello'];
$scope.sayHello = function() {
alert(greetings.join());
}
this.addGreeting = function(greeting) {
greetings.push(greeting);
}
}
};
})
.directive('finnish',function() {
return {
restrict: 'A',
require: 'greeting',
link: function(scope, element, attrs, controller) {
controller.addGreeting('hei');
}
}
})
.directive('hindi',function() {
return {
restrict: 'A',
require: 'greeting',
link: function(scope, element, attrs, controller) {
controller.addGreeting('नमस्ते');
}
}
});
These directives work fine, however, if I change the greeting controller to receive an external controller via an attribute like this:
.directive('greeting',function() {
return {
restrict: 'E',
replace: true,
template: "<button class='btn' ng-click='sayHello()'>Say Hello</button>",
controller: '#',
name: 'ctrl'
};
})
And make a reference in the HTML like this:
<!DOCTYPE html>
<html ng-app="eventsApp">
<head lang="en">
<meta charset="UTF-8">
<title>Event Registration</title>
<link rel="stylesheet" href="css/bootstrap.min.css"/>
<link rel="stylesheet" href="css/app.css"/>
</head>
<body>
<greeting ctrl="GreetingController">
<div finnish hindi></div>
</greeting>
<script src="lib/jquery.min.js"></script>
<script src="lib/angular/angular.js"></script>
<script src="lib/angular/angular-resource.js"></script>
<script src="lib/angular/angular-route.min.js"></script>
<script src="lib/underscore-1.4.4.min.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers/GreetingController.js"></script>
<script src="js/directives/greeting.js"></script>
<script src="js/filters.js"></script>
<script src="lib/bootstrap.min.js"></script>
</body>
</html>
The other directives stop working, angular logs the following error:
Error: [$compile:ctreq] Controller 'greeting', required by directive 'hindi', can't be found!
I imagine that there is a way to fix this, but since I'm new in Angular I'm quite a bit lost.
If you are getting the controller as an attribute, the attribute name needs to be the name of the directive:
<greeting greeting="GreetingController" finnish="" hindi=""></greeting>
See this plunker

Categories