1

I am trying to learn a little about AngularJS. I have created websites in ASP.NET before so I decided to try to create an AngularJS site with MVC. I downloaded this excellent example: https://github.com/jph00/AngularTutorial/tree/master/AngularTutorial I created my own site based upon it but I have a problem with the dependency injection in the AngularJS code. I created a class called Hotel

public class Hotel
{

    public int HotelId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string PostalCode { get; set; }
    public string Country { get; set; }
    public string Notes { get; set; }
}

In the AngularJS code I have a file called Emp.js

    var HotelApp = angular.module('HotelApp', ['ngResource']).

HotelApp.factory('Hotel', function ($resource) {
return $resource('/api/Hotel/:HotelId', { HotelId: '@HotelId' }, { update: { method: 'PUT' } });});

I also have HotelApp declared in the div tag of the page where I need it;

<div ng-app="HotelApp" data-ng-controller="hotelController" class="container">

However when I set breakpoints and jump to them, Hotel is always undefined. The only difference between the GitHub example and my project is that my project uses cshtml (the GitHub example is html). I have not seen many examples online of dependency injection with AngularJS but those I have seen don't use instantiable classes (as my example has). Is there any example out there of AngularJS like this (dependency injection in an MVC project using a class)?

Edit:this is the Controller class;

{
public class HotelController : ApiController
{
    private HotelsContext db = new HotelsContext();
    // GET api/<controller>
    [HttpGet]
    public IEnumerable<Hotel> Get()         
    {
        return db.Hotels.AsEnumerable();
    }

    // GET api/<controller>/5
    public Hotel Get(int id)
    {
        Hotel hotel = db.Hotels.Find(id);
        if (hotel == null)
        {
            throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
        }

        return hotel;
    }

    // POST api/<controller>
    public HttpResponseMessage Post(Hotel hotel)
    {
        if (ModelState.IsValid)
        {
            db.Hotels.Add(hotel);
            db.SaveChanges();

            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, hotel);
            response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = hotel.HotelId }));
            return response;
        }
        else
        {
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
        }
    }

    // PUT api/<controller>/5
    public HttpResponseMessage PutHotel(int id, Hotel hotel)
    {
        if (!ModelState.IsValid)
        {
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
        }

        if (id != hotel.HotelId)
        {
            return Request.CreateResponse(HttpStatusCode.BadRequest);
        }

        db.Entry(hotel).State = EntityState.Modified;

        try
        {
            db.SaveChanges();
        }
        catch (DbUpdateConcurrencyException ex)
        {
            return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
        }

        return Request.CreateResponse(HttpStatusCode.OK);
    }

    // DELETE api/<controller>/5
    public HttpResponseMessage Delete(int id)
    {
        Hotel hotel = db.Hotels.Find(id);
        if (hotel == null)
        {
            return Request.CreateResponse(HttpStatusCode.NotFound);
        }

        db.Hotels.Remove(hotel);

        try
        {
            db.SaveChanges();
        }
        catch (DbUpdateConcurrencyException ex)
        {
            return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
        }

        return Request.CreateResponse(HttpStatusCode.OK, hotel);
    }

    protected override void Dispose(bool disposing)
    {
        db.Dispose();
        base.Dispose(disposing);
    }
}

}

The AngularJS controller is;

function hotelController($scope, $http) {  
$scope.loading = true;
$scope.addMode = false;

//Used to display the data
$http.get('/api/Hotel/').success(function (data) {        
    $scope.hotels = data;
    $scope.loading = false;
})
.error(function () {
    $scope.error = "An Error has occured while loading posts!";
    $scope.loading = false;
});

$scope.toggleEdit = function ($scope, $location, $routeParams, Hotel) {
    alert("Edit 1");
    $scope.action = "Update";
    alert("Edit 2");
    id = $scope.HotelId;
    alert("id is " + id);

    // $scope.item = Todo.get({ id: id });
    this.hotel.editMode = !this.hotel.editMode;

};
//Used to save a record after edit
$scope.save = function ($scope, $location, $routeParams, Hotel) {
    alert("scope item");
    alert("Hotel " + Hotel.id);
    $scope.item = Hotel.get({ id: id });
    alert("scope.item" );
    Hotel.update({ id: id }, $scope.item, function () {
       // $location.path('/');
        alert("id is " + id);
    });
};


//Used to add a new record
$scope.add = function () {        
    $scope.loading = true;
    $http.post('/api/Hotel/', this.newhotel).success(function (data) {
        alert("Added Successfully!!");
        $scope.addMode = false;
        $scope.hotels.push(data);
        $scope.loading = false;
    }).error(function (data) {
        $scope.error = "An Error has occured while Adding Friend! " + data;
        $scope.loading = false;

    });
};

//Used to edit a record
$scope.deletefriend = function () {       
    $scope.loading = true;
    var friendid = this.hotel.FriendId;
    $http.delete('/api/Hotel/' + friendid).success(function (data) {
        alert("Deleted Successfully!!");
        $.each($scope.hotels, function (i) {
            if ($scope.hotels[i].FriendId === friendid) {
                $scope.hotels.splice(i, 1);
                return false;
            }
        });
        $scope.loading = false;
    }).error(function (data) {
        $scope.error = "An Error has occured while Saving Friend! " + data;
        $scope.loading = false;

    });
};

}

5
  • Where is your controller code? Commented Aug 13, 2014 at 14:00
  • I just added it to the end now Commented Aug 13, 2014 at 14:22
  • Post angularjs controller not mvc. Commented Aug 13, 2014 at 14:23
  • I just added the angularjs controller now Commented Aug 13, 2014 at 14:31
  • take a look at my answer below. Commented Aug 13, 2014 at 14:32

2 Answers 2

1

This has been resolved for me. The problem was the controller function had to be changed to get a reference to the Hotel class. It was

function hotelController($scope, $http) {

but is now

function hotelController($scope, Hotel) {

If anybody needs further clarification contact me.

Sign up to request clarification or add additional context in comments.

Comments

0

You need to define your controller and pass Hotel as a dependency.

DEMO

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

HotelApp.factory('Hotel', [function() {
    return {
        run: function() {
            alert("run");
        }
    }
}]);

HotelApp.controller("hotelController", ["$scope", "Hotel",
  function($scope, Hotel) {
      Hotel.run();
  }
]);

Good read on dependency injection in angular.

EDIT:

Remove $scope, $location, $routeParams and Hotel parameters. You need to add those as dependency in your controller like in the example above.

$scope.toggleEdit = function($scope, $location, $routeParams, Hotel) {
   alert("Edit 1");
   $scope.action = "Update";
   alert("Edit 2");
   id = $scope.HotelId;
   alert("id is " + id);

   // $scope.item = Todo.get({ id: id });
   this.hotel.editMode = !this.hotel.editMode;

};

//Used to save a record after edit
$scope.save = function($scope, $location, $routeParams, Hotel) {
   alert("scope item");
   alert("Hotel " + Hotel.id);
   $scope.item = Hotel.get({ id: id });
   alert("scope.item");
   Hotel.update({ id: id }, $scope.item, function() {
      // $location.path('/');
         alert("id is " + id);
       });
 };

7 Comments

Thank you for your reply. I tried your code but "Hotel" is still 'undefined' when I hover the mouse over it. When I put $scope in the Immediate window I can get at the properties of that, just not Hotel
Thank you for the link. The example in it is similar to what I have seen before: "myFactory" is injected (with .factory) but I don't see what "myFactory" is. My equivalent is Hotel which is a class with properties.
In your code, when I set a breakpoint on "HotelApp.factory('Hotel', [function () and hit F11, it jumps into the middle of angular.min.js. In the example on GitHub github.com/jph00/AngularTutorial/tree/master/AngularTutorial) on the equivalent line (.factory) it jumps into this line in angular.js: invokeQueue[insertMethod || 'push']([provider, method, arguments]);
make sure factory and controller are in same module or if they are in different then inject that module in root module.
When you say the same module do you mean the file (.js file) or the same folder?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.