向$ resource prototype添加一个函数

时间:2014-05-27 21:16:19

标签: javascript angularjs prototype

我正在尝试将视图函数添加到Angular $资源中。我通过原型将它添加到$ resource中,但出于某种原因,' this'原型函数中的引用不正确,因此所有属性都是未定义的。奇怪的是,在console.log中,这似乎具有正确返回所需的所有属性。

http://plnkr.co/edit/YsTlAztjEKjn3piQAem2?p=preview

app.factory("Now", function($resource) {

  var Now = $resource("http://date.jsontest.com/");

  Now.prototype.$dateTime = function() {
    console.log("2", this); // this has date and time properties, good
    return this.date + " " + this.time;
  };

  return Now;
});

app.controller("TestController", function(Now) {
  var now = new Now();
  now.$get();
  console.log("1", now); // prototype has the $dateTime function!
  console.log("3", now.$dateTime()); // but it returns undefined, bad
});

3 个答案:

答案 0 :(得分:4)

实际上,您的错误是您在资源返回数据之前调用$ dateTime。

请参阅此plunk

我上面的答案似乎有效的唯一原因是它被插值,当资源最终返回时,datetime函数被称为AGAIN。但如果你要保持代码相同,它仍然会失败

答案 1 :(得分:3)

您正在尝试使用this的属性,同时仍在从服务器获取模型,导致这些属性在您请求时未定义。您需要使用从$get返回的对象上可用的promise方法,以保证请求已完成。

now.$get();

应该成为这个

now.$get().then(function() { console.log("1", now); console.log("3", now.$dateTime()); });

答案 2 :(得分:1)

您的错误在于使用.factory。它期望返回一个对象,但$ resource是一个函数。将其更改为.service,它将起作用

app.service("now", function($resource) {

完整代码:http://plnkr.co/edit/n31MMNTlKV3i04HdXUms?p=catalogue

var app = angular.module("test", ["ngResource"]);

app.service("now", function($resource) {

  var now = $resource("http://date.jsontest.com/");

  now.prototype.dateTime = function() {
    return this.date + " " + this.time;
  };

  return now;
});

app.controller("TestController", function($scope, now) {
  $scope.now = now.get();
});