我是angularJS的新手。目前正致力于服务。我试图将文本框值传递给服务。我不知道怎么过。我编码,但它不起作用。
app.service("wishService", function ($timeout) {
this.wishHim = function (_wishMessage) {
$timeout(function () {
alert('Hi ,' + _wishMessage);
}, 2000);
}
});
app.controller('wishCtrl', ['$scope', function ($scope, wishService) {
$scope.Message = "";
$scope.SendMessage = function (wishMessage) {
wishService.wishHim(wishMessage);
};
}]);
<div ng-controller="wishCtrl">
Wish Message: <input type="text" ng-model="wishMessage" />
<input type="button" value="Send Message" ng-click="SendMessage(wishMessage)" /><br />
Your Message : {{Message}}
</div>
答案 0 :(得分:5)
wishService 注入问题
app.controller('wishCtrl', ['$scope', 'wishService', function ($scope, wishService) {
$scope.Message = "";
$scope.SendMessage = function (wishMessage) {
wishService.wishHim(wishMessage);
};
}]);
答案 1 :(得分:0)
我已修复您的代码,请在此处查看PLUNK。虽然Sandeep说的是正确的,但你也有其他一些问题。请参阅我更改的内容。
编辑:我注意到我改变你的代码的是工厂的格式,而不是服务:
app.service("MessageService", function () {
var service = {
msg: undefined,
setMsg: function(msg){
this.msg = msg;
},
getMsg: function(msg){
return this.msg;
}
}
return service;
});