My issue: I have an input for a user to input a new tweet to post to twitter. However, when executing the function postTweet() after an ng-click, $scope.newStatus appears to be empty when it reaches the factory. (as seen in the console.log). What am I doing wrong in attempt to pass $scope.newStatus as the status parameter for the the postTweet factory function?
On a side note. If i define $scope.newStatus = 'testing 123' in the controller, it works properly.
All help is appreciated greatly.
<input type="text" ng-model="newStatus" placeholder="enter new tweet"> {{newStatus}}
<button ng-click="postTweet()">
Factory:
'use strict';
angular
.module('m01-profile')
.factory('Profile', [
'$http', '$q', 'apiRef', 'Authentication',
function($http, $q, apiRef, Authentication) {
var authentication = Authentication.data.authData;
var service = {
postTweet: function(newStatus){
console.log(newStatus);
var deferred = $q.defer();
var requestObject = {
headers: { 'Content-Type' : 'application/json' },
token: authentication.twitter.accessToken,
tokenSecret: authentication.twitter.accessTokenSecret,
status: newStatus
};
$http.post(apiRef + 'twitter/update_status', requestObject)
.success(function(data, status, headers, config) {
deferred.resolve(newStatus);
}).
error(function(data, status, headers, config) {
deferred.reject('Unable to post new status to twitter');
});
return deferred.promise;
}
};
return service;
}]);
Controller
'use strict';
angular
.module('m01-profile')
.controller('ProfileController', [
'$scope', '$log', 'Profile',
function($scope, $log, Profile) {
$scope.postTweet = function(){
Profile.postTweet($scope.newStatus).then(function(success){
}, function(error){
});
};
}
]);
Try something like this:
Controller:
HTML:
As someone commented already, in order to get two-way data binding in angular you need to bind
ng-model
to an object property rather than a string primitive.In your original code, the
input
wasn't updating$scope.newStatus
variable becauseng-model
was bound to a string primitive.