我有这个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>
看起来像:
我为指令创建了一个隔离范围:
scope:
{
number: '@',
makeCall: '&'
}
哪里
number
值被视为来自attibute的字符串 makeCall
值取自实际通过以下方式发送消息的html:
ng-click="makeCall({message: value, number: number , company:network})"
其中makeCall
“已链接”至leaveVoiceMail
方法。
问题
除了一件事之外一切正常 - 当我点击按钮时:
为什么我会在警告框中显示undefined
?
我做发送值,我希望得到:
通过( AT&amp; T )
向123发送问候语
我做错了什么?
答案 0 :(得分:1)
您的主HTML中company
和network
不匹配。在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>
答案 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)"