Angularjs依赖注入一个可实例化的类

时间:2014-08-13 13:53:10

标签: angularjs dependencies code-injection

我想了解一下AngularJS。我之前在ASP.NET中创建了网站,因此我决定尝试使用MVC创建一个AngularJS网站。我下载了这个很好的例子: https://github.com/jph00/AngularTutorial/tree/master/AngularTutorial 我基于它创建了自己的站点,但我在AngularJS代码中遇到依赖注入问题。 我创建了一个名为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; }
}

在AngularJS代码中,我有一个名为Emp.js的文件

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

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

我还在我需要的页面的div标签中声明了HotelApp;

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

但是,当我设置断点并跳转到它们时,酒店始终未定义。 GitHub示例和我的项目之间的唯一区别是我的项目使用cshtml(GitHub示例是html)。 我没有在网上看到很多关于使用AngularJS进行依赖注入的例子,但是我看到的那些没有使用可实例化的类(如我的例子所示)。是否有像这样的AngularJS的例子(使用类的MVC项目中的依赖注入)?

编辑:这是Controller类;

{
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);
    }
}

}

AngularJS控制器是;

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;

    });
};

}

2 个答案:

答案 0 :(得分:1)

这已经为我解决了。问题是必须更改控制器功能以获取对酒店类的引用。 这是

function hotelController($ scope,$ http){

但现在是

function hotelController($scope, Hotel) {

如果有人需要进一步澄清,请与我联系。

答案 1 :(得分:0)

您需要定义控制器并将Hotel作为依赖项传递。

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.

修改

删除$ scope,$ location,$ routeParams和酒店参数。您需要在控制器中添加这些依赖项,如上例所示。

$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);
       });
 };