我第一次接受依赖注射。我的目标是最终只在两个控制器之间启用一些简单的通信。我甚至没有足够甚至担心处理与第二个控制器的通信。我收到了ContactMessages.AddNewContact(response.data)的“不是函数错误”;
当我使用self.ContactMessages.AddNewContact(response.data);我得到“无法读取未定义的属性'AddNewContact'”
我只想调用ContactMessages工厂的AddNewContact函数。
这应该是一个相当基本的程序。
<html ng-app="myApp"><head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<script>
var userName = 'some email'; //pseudo code
var app = angular.module('myApp', []);
app.factory('ContactMessages', [function()
{ var tmpContact = {};
this.AddNewContact = function(objContact){
this.tmpContact = objContact;
};
return tmpContact;
}]);
app.controller('ActionsController', function ($scope, $http, ContactMessages){
this.newContact = {
Email: "",
Type: "",
Frequency: "",
UserName: userName
};
var self = this;
this.AddContact=function()
{
$http({
method: 'POST',
url: 'some url', //pseudo code
data: this.newContact,
headers: { 'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function successCallback(response)
{ if(angular.isObject(response.data))
self.ContactMessages.AddNewContact(response.data);
}, function errorCallback(response) {
});
};
});
</script>
</head>
<body ng-controller="ActionsController as ActCtrl">
<div>
<form name="frmAddContact" noValidate>
<input placeholder="Contact Email" type="email" ng-model="ActCtrl.newContact.Email" required></input>
<select ng-model="ActCtrl.newContact.Type" required>
<option value="">Contact Type</option>
<option value="COLLEAGUE">Colleague</option>
<option value="FRIEND">Friend</option>
<option value="FAMILY">Family</option>
</select>
<select ng-model="ActCtrl.newContact.Frequency" required>
<option value="">Contact Frequency</option>
<option value="ANY">Any Time</option>
<option value="WEEKLY">Weekly</option>
<option value="MONTHLY">Monthly</option>
<option value="QUARTERLY">Quarterly</option>
<option value="YEARLY">Yearly</option>
</select>
<div >
<button ng-click="ActCtrl.AddContact()" ng-disabled="frmAddContact.$invalid" >Add Contact</button>
</div>
</form>
</div></body></html>
答案 0 :(得分:1)