Reputation: 23
I'm having my first go at dependency injection. My goal is to eventually just enable some simple communication between two controllers. I'm not even getting far enough to even worry about handling the communication with the second controller. I'm getting an "is not a function error" for ContactMessages.AddNewContact(response.data);
When I use self.ContactMessages.AddNewContact(response.data); I get "Cannot read property 'AddNewContact' of undefined"
I just want to invoke the AddNewContact function of the ContactMessages factory.
This should be a fairly basic procedure.
<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>
Upvotes: 0
Views: 379
Reputation: 2962
Hi change your Factory like this
app.factory('ContactMessages', [
function () {
var o = {};
o.AddNewContact = {};
return o;
}
]);
for refrence https://plnkr.co/edit/sYSJ5ZOVQUX0ctir2EmM?p=preview
Upvotes: 1