从 AngularJS 中的指令调用父控制器的方法 [英] calling method of parent controller from a directive in AngularJS

查看:23
本文介绍了从 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>

和脚本:

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 是未定义的.

when the updatePerson method gets called, person is undefined.

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

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

推荐答案

只需简单地改变你的 html 如下

Just simple change your html as below

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

      </my-directive>

您没有通过 updatePerson 传递person",这就是它不起作用的原因

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

这篇关于从 AngularJS 中的指令调用父控制器的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆