小编典典

从AngularJS中的指令调用父控制器的方法

angularjs

在上一个问题之后,我现在尝试从指令中调用父控制器上的方法。我得到一个未定义的参数。这是我的工作:

<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>

和脚本:

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: '&' }
            }
        }
    )

调用updatePerson方法时,person是未定义的。

jsfiddle在这里:http :
//jsfiddle.net/graphicsxp/Z5MBf/7/


阅读 273

收藏
2020-07-04

共1个答案

小编典典

只需简单地如下更改您的html

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

      </my-directive>

您没有通过updatePerson传递“人”,这就是为什么它不起作用

2020-07-04