Christine268
Christine268

Reputation: 732

How do I get this AngularJS service working in my code?

Here is the code for my service. It is taken almost exactly from the first answer here.

var myApp = angular.module('myApp', ['ngRoute']);

       myApp.service('sharedProperties',function(){
           var property = "First";

           return{
               getProperty:function(){
                   return property;
               },
               setProperty:function(value){
                   property = value;
               }
           };
       });

Here is the JSFiddle that shows my code in full and it not working.

The error I get is:

"Error: sharedProperties is not defined

For the line that the alert is on. I am just using an alert as a mere example of showing that the service is working before I extend the code further.

Anyone know why this simple example of a service is not working? I've thoroughly went over the code to make sure there are no typos or anything silly like that.

The answer that I linked has a JSFIDDLE that uses an older version of AngularJS. I was able to replace it with the version Angular being used in my JSFIDDLE and it still worked fine so it doesn't seem to be a version issue.

Upvotes: 0

Views: 41

Answers (2)

pro
pro

Reputation: 792

You need to inject the service in your controller.

Here is the fiddle https://jsfiddle.net/b2fCE/732/

myApp.controller('mainController', function($scope, sharedProperties) {
        // create a message to display in our view
        $scope.message = 'Everyone come and see how good I look!';

        alert(sharedProperties.getProperty());
    });

Upvotes: 0

tymeJV
tymeJV

Reputation: 104775

You need to inject the service to your controller:

myApp.controller('mainController', function($scope, sharedProperties) {

(Minification safe syntax)

myApp.controller('mainController', ["$scope", "sharedProperties", function($scope, sharedProperties) {

Working fiddle: http://jsfiddle.net/b2fCE/733/

Upvotes: 1

Related Questions