AngularJS自定义服务无法正常工作

时间:2017-01-18 23:47:00

标签: javascript angularjs

这是我创建的一项简单服务:

void Main()
{

    var serviceAppointment = new Entity("serviceappointment")
    {
        Attributes = new AttributeCollection() { { "resources", GetResources() } }
    };

    var sa = serviceAppointment.GetAttributeValue<EntityCollection>("resources");

    Console.WriteLine(sa.Entities.Count);
}

public EntityCollection GetResources()
{
    var entityList = new List<Entity>();
    entityList.Add(new Entity("resource")
    {
        Attributes = new AttributeCollection() { { "name", "Truck" }}
    });

    entityList.Add(new Entity("resource")
    {
        Attributes = new AttributeCollection() { { "name", "Tool" } }
    });

    return new EntityCollection(entityList);

}

这是我想要使用该服务的控制器:

var app = angular.module('myApp', ['ngRoute']);
app.service('UserService', function() {

this.user = {firstName:"",middleName:"",lastName:"",email:"",dob:""};
this.addUser = function (user) {
  users.push(user);
}
this.displayUser = function (user) {
  this.user = user;
}
});

这是我将用户对象传递给用户指令的HTML:

app.controller('DisplayUserController', ['$scope','UserService', 
function($scope, UserService) {

$scope.user = UserService.user;

}]);

为什么我收到“未知提供商:userProvider&lt; - user”错误?请帮忙。

2 个答案:

答案 0 :(得分:0)

您需要将ngModel绑定到您的指令:

.directive('user', function() {
  return {
    restrict: 'E',
    scope:{
      'user': '=ngModel'
    },
    templateUrl:'display-single-user.html',
    controller: function($scope) {
        var user = $scope.user;
        $scope.firstName = user.firstName;
        $scope.middleName = user.middleName;
        $scope.lastName = user.lastName;
        $scope.email = user.email;
        $scope.dob = user.dob;
    }
  };
});

答案 1 :(得分:0)

我的指令存在问题,我使用的内部控制器也需要UserService,因此将其添加为依赖项并开始工作。现在,如果这是一个正确的做法,请告诉我。

angular.module('myApp').directive('user', ['UserService', function() {
  return {
     restrict: 'E',
     templateUrl:'templates/display-single-user.html',
     controller: function($scope, UserService) {

         $scope.firstName = UserService.user.firstName;
         $scope.middleName = UserService.user.middleName;
         $scope.lastName = UserService.user.lastName;
         $scope.email = UserService.user.email;
         $scope.dob = UserService.user.dob;
     }
  };
}]);