参数不是从指令发送到控制器的吗?

时间:2015-10-17 18:20:50

标签: angularjs

我有这个Controller,它有一种发送消息的方法:

var app = angular.module('phoneApp', []);

app.controller('appCtrl', ['$scope', function($scope)
{
    $scope.leaveVoiceMail = function(number,message ,company)
    {
        alert("sending " + message + " to " + number + " via(" + company + ")");
    }
}]);

一个Factory服务,其中包含一些通信提供商的数据:

app.factory('myFac', [function()
{
    return {
        networksArr: ["Verizon", "AT&T", "Sprint"]
    };
}])

Phone directive

app.directive('phone', ['myFac', function(myFac)
{
    return {
        restrict: 'E',
        scope:
        {
            number: '@',
            makeCall: '&'
        },
        templateUrl: 't.html',
        link: function(scope)
        {
            scope.networksArr = myFac.networksArr;
            scope.network = scope.networksArr[0];
        }
    };
}]);

每部手机都是:

的模板(t.html
<div>
  Number: {{number}} <br>
  Network:<select ng-model="network" ng-options="net for net in networksArr"></select>{{network}}
</div>
<input type="text" ng-model="value" placeholder="Enter phone">
<input   type="button" value="Call Home!" ng-click="makeCall({message: value, number: number , company:network})">

所以这是基本的HTML:

<div ng-app="phoneApp">
    <div ng-controller="appCtrl">
        <phone number="123"   make-call="leaveVoiceMail(number,message,network)"></phone>
        <phone number="124"   make-call="leaveVoiceMail(number,message,network)"></phone>
        <phone number="125"   make-call="leaveVoiceMail(number,message,network)"></phone>
    </div>
</div>

看起来像:

enter image description here

我为指令创建了一个隔离范围:

 scope:
       {
        number: '@',
        makeCall: '&'
       }

哪里

  • number值被视为来自attibute的字符串
  • makeCall值取自实际通过以下方式发送消息的html:

    ng-click="makeCall({message: value, number: number , company:network})"

其中makeCall “已链接”leaveVoiceMail方法。

问题

除了一件事之外一切正常 - 当我点击按钮时:

enter image description here

为什么我会在警告框中显示undefined

发送值,我希望得到:

  

通过( AT&amp; T

向123发送问候语

我做错了什么?

Plunker

2 个答案:

答案 0 :(得分:1)

您的主HTML中companynetwork不匹配。在phone元素中,使用company。它必须是公司,因为它在控制器方法中的名称是什么,它也是你在指令中引用的内容。

<phone number="123"   make-call="leaveVoiceMail(number,message,company)"></phone>
<phone number="124"   make-call="leaveVoiceMail(number,message,company)"></phone>
<phone number="125"   make-call="leaveVoiceMail(number,message,company)"></phone>

Plunker:http://plnkr.co/edit/roqVte?p=preview

答案 1 :(得分:1)

可能只是您的错字,但在模板中您传递的是company局部变量:

ng-click="makeCall({message: value, number: number , company:network})"

但请使用network

make-call="leaveVoiceMail(number,message,network)"

应该是:

make-call="leaveVoiceMail(number,message,company)"