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

查看:474
本文介绍了调用父控制器的方法从AngularJS指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

随着我的previous <一个href=\"http://stackoverflow.com/questions/15990122/passing-object-to-angularjs-directive-from-the-controller\">question,现在我想从我的指令调用父控制器上的方法。我得到一个未定义的参数。这是我做的:

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方法被调用,人是不确定的。

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这就是为什么它不工作

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

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

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