ANJYR
ANJYR

Reputation: 2623

AngularJS: Pass textbox value to services

I am new in angularJS. Currently working on services. I tried to pass text-box value to services. I don't know how to pass. I code but it's not working.

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>

DEMO

Upvotes: 1

Views: 1245

Answers (2)

VSO
VSO

Reputation: 12646

I fixed your code, see the PLUNK here. While what Sandeep said is correct, you also had a TON of other problems. Refer to what I changed.

Edit: It was brought to my attention that what I changed your code to is the format of a factory, rather than a service:

app.service("MessageService", function () {

var service = {
  msg: undefined,

  setMsg: function(msg){
    this.msg = msg; 
  },

  getMsg: function(msg){
    return this.msg; 
  }
}

return service;
});

Upvotes: 0

Sandeep
Sandeep

Reputation: 1479

wishService injection problem

app.controller('wishCtrl', ['$scope', 'wishService', function ($scope, wishService) {    
    $scope.Message = "";
    $scope.SendMessage = function (wishMessage) {
        wishService.wishHim(wishMessage);
    };
}]);

Upvotes: 5

Related Questions