简体   繁体   English

在angularJS中绑定服务数据

[英]Binding service data in angularJS

I have a service that is used to share data between 2 controllers and retrieves a data list: 我有一个用于在2个控制器之间共享数据并检索数据列表的服务:

myApp.service('DataService', function($http) {
    this.data = [];
    this.loadData = function() {
        $http.get('/api/data').success(function(data) {
            this.data= data;
        })
    };

});

which is called in my controller: 在我的控制器中称为:

myApp.controller('appController', function($scope, DataService) {
    $scope.DataService= DataService;
    DataService.loadData();
});

and displayed here: 并显示在这里:

<div ng-controller="appController">
    <li ng-repeat='item in DataService.data'>
        <a href="#item/{{item.ID}}"> View Item</a>
    </li>
</div>

When this is ran, it doesn't display anything. 当它运行时,它不会显示任何内容。 I have ran it with some alert boxes and can see that the data list is populated with the data I want to display but no information is displayed otherwise. 我已经用一些警报框运行了它,可以看到数据列表中填充了我要显示的数据,但否则未显示任何信息。

You're using your service incorrectly. 您使用的服务不正确。 Right now, it's going to be hard for Angular to watch the property on your service for changes. 目前,Angular很难监视服务上的属性以进行更改。 Instead of storing the data as a property on itself, it should simply return it to the caller. 与其将数据存储为自身的属性,不如将数据简单地返回给调用方。 Try: 尝试:

myApp.service('dataService', function($http) {
    this.loadData = function() {
        return $http.get('/api/data').then(function(data) { return data; });
    }
}

Which is then called in the controller like: 然后在控制器中调用它,例如:

myApp.controller('appController', function($scope, dataService) {
    $scope.data = dataService.loadData();
});

And bound to in the view like: 并绑定到这样的视图中:

<div ng-controller="appController">
    <li ng-repeat="item in data track by $id">
        <a href="#item/{{ item.ID }}">View Item</a>
    </li>
</div>

Have to return a promise and use .then to access it: 必须返回一个诺言并使用.then来访问它:

this.loadData = function() {
    return $http.get('/api/data').then(function(data) {
        return data.result
    })
};

Ctrl: Ctrl:

DataService.loadData().then(function(data) {
    $scope.DataService = data;
});

不知道我是否正确,但是...通过在服务本身而不是在分配给$ scope的服务上调用方法不会使Angular JS完全错过对data属性的监视吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM