1

我需要将数据从控制器传递到 html 模板。我可以看到来自 console.log 的数据,但我没有通过 DOM 看到它。

这是我的组件:

import ItemService from '../../services/test.service.js'

const TestComponent = {
    controllerAs: 'testCtrl',
    controller: function ($http) {
                    ItemService.getItems($http)
                    .then(data => {
                        this.items = data.categories;
                        console.log('inside controller', this.items);
                        })
    },
    template: require('./test.html'),
    bindings: {

    }
};

export default TestComponent;

这是模板:./test.html

<div class="test">
    NAMES OF ITEMS:
    <ul>
        <li ng-repeat="item in testCtrl.items">
          <p>{{item.name}}</p>
        </li>
      </ul>
</div>

为什么我看不到列表?

4

2 回答 2

0

如果是您的控制器并且仍然没有显示,则可能数据没有被范围消化,这是 angularjs 中承诺的常见事情,您需要在分配$scope.$digest()之后强制使用,或者

$scope.$apply(function(){
//assign inside here
});

如果您处于一个摘要周期的中间,这可能会导致问题,因此更好的方法是使用 $timeout:

$timeout(() => {
//assign here
});
于 2018-01-19T20:00:24.880 回答
0

我相信this可能在 $http 的回调中改变了上下文。它不再指向您的控制器。

尝试将控制器上下文的引用存储在局部变量中(例如:)self

var self = this;
ItemService.getItems($http)
.then(data => {
    self.items = data.categories;
    console.log('inside controller', self.items);
})
于 2018-01-19T15:14:25.440 回答