【发布时间】:2015-08-27 20:51:27
【问题描述】:
我的问题:我有一个输入供用户输入一条新推文以发布到推特。但是,在 ng-click 后执行函数 postTweet() 时,$scope.newStatus 在到达工厂时似乎为空。 (如 console.log 中所示)。尝试将 $scope.newStatus 作为 postTweet 工厂函数的状态参数传递时,我做错了什么?
附带说明。如果我在控制器中定义 $scope.newStatus = 'testing 123',它可以正常工作。
非常感谢所有帮助。
<input type="text" ng-model="newStatus" placeholder="enter new tweet"> {{newStatus}}
<button ng-click="postTweet()">
工厂:
'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;
}]);
控制器
'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){
});
};
}
]);
【问题讨论】:
-
我为您的样本创建了一个简单的 plunker,但无法重现该行为。 plnkr.co/edit/4nrMFiIB4strDwQtVeSF?p=preview
-
话虽如此,您在这里使用的是动态原语,由于 JavaScript 原型继承,它可能超出代码中任何数量的范围。见stackoverflow.com/questions/14049480/…。
-
谢谢@Claies :) 我添加了 $parent.newStatus 只是为了检查它是否是继承问题。结果就是这样!
标签: javascript angularjs parameter-passing