Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
984 views
in Technique[技术] by (71.8m points)

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/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...