Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling method of parent controller from a directive in AngularJS

Following my previous question, I'm now trying to call a method on the parent controller from my directive. I get an undefined parameter. Here's what I do:

<body ng-app="myApp" ng-controller="MainCtrl">   <span>{{mandat.rum}}</span>   <span>{{mandat.surname}}</span> <input type="text" ng-model="mandat.person.firstname" /> <my-directive mandate-person="mandat.person" updateparent="updatePerson()" >    </my-directive> </body> 

And the script:

var app = angular.module('myApp', []);      app.controller('MainCtrl', function ($scope) {         $scope.mandat = { name: "John", surname: "Doe", person: { id: 1408, firstname: "sam" } };         $scope.updatePerson = function(person) {             alert(person.firstname);           $scope.mandat.person = person;            }     });       app.directive('myDirective', function () {         return {             restrict: 'E',             template: "<div><span>{{mandatePerson.id}}<span><input type='text' ng-model='mandatePerson.firstname' /><button ng-click='updateparent({person: mandatePerson})'>click</button></div>",             replace: true,             scope: { mandatePerson: '=', updateparent: '&' }             }         }     ) 

when the updatePerson method gets called, person is undefined.

jsfiddle here : http://jsfiddle.net/graphicsxp/Z5MBf/7/

like image 486
Sam Avatar asked Apr 13 '13 18:04

Sam


People also ask

How do you call a method in a directive?

Inside the directive it is creating an updateMap() method on the scope object in the directive and then calling the setFn() method which is mapped to the $scope. setDirectiveFn() method by this line: <map set-fn="setDirectiveFn(theDirFn)"></map> in your HTML and this line: scope: { setFn: '&' } in your directive.

How do I get parent scope in directive?

You can still access the parent scope using $parent , but this is not normally recommended. Instead, you should specify which parent scope properties (and/or function) the directive needs via additional attributes on the same element where the directive is used, using the = , @ , and & notation.

What is $parent in AngularJS?

$scope.$parent refers to the $scope of the parent element.

Which directive is used for controller in angular?

AngularJS ng-controller Directive The ng-controller directive adds a controller to your application. In the controller you can write code, and make functions and variables, which will be parts of an object, available inside the current HTML element. In AngularJS this object is called a scope.


1 Answers

Just simple change your html as below

<my-directive mandate-person="mandat.person" updateparent="updatePerson(person)" >        </my-directive> 

you are not passing "person" with updatePerson thats why it is not working

like image 102
Ajay Beniwal Avatar answered Oct 14 '22 20:10

Ajay Beniwal