将服务中的变量注入html

时间:2015-10-16 13:46:56

标签: javascript angularjs

我被要求在角度JS应用程序中调试一些东西,问题是我对这个框架一无所知,我需要完成这个。

我需要将一个变量从我的服务注入一个html模板。 所以我想我需要从Controller获取这个变量,它从服务中获取它。

目前我有这个:

controller.js

$scope.fileURL = null;
var fileURL = ItemsService.fileURL;
$scope.fileURL.push(fileURL);

services.js

我在服务类中声明了这个:

this.fileURL = null;

我以这种方式宣布我的方法:

self.fileURL = fileURL;

但我收到此错误TypeError: Cannot call method 'push' of null 并定义了fileURL并在我的方法中获得了一个值。 知道为什么吗?

由于

1 个答案:

答案 0 :(得分:2)

更高效的解决方案

感谢他对他的评论的忠诚。

通过$ scope使您的服务可见:

$scope.itemService = ItemService;

并在模板中使用它,例如:

{{itemService.fileURL}}

将更具性能,更简单,并具有所有其他优势。

旧解决方案

为什么不直接传递你的变量:

在您的服务中:

this.fileURL = "something";

在您的控制器中:

$scope.fileURL = function() {
    return ItemsService.fileURL;
};

这样,您的服务所做的更改(如更新fileURL将触发通过控制器更新视图。

<强>供参考:

如果你定义你的$ scope-variable:

Object.defineProperty($scope, 'fileURL', {
    get: function() {
        return ItemService.fileURL;
    },
    set: function(newValue) {
        ItemService.fileURL = newValue;

    }
});

您也可以从控制器更新服务中的变量 AND childscopes将具有相同的功能,因为在$scope.fileURL = 'different';时,他们不会引入隐藏原始属性的新属性fileURL一个,不再连接到服务了。