看起来很简单,但我听不懂。所以我有HTML

<div class="ui three column grid" data-bind="foreach: stories">
  <div class="column">
    <div class="ui stacked segment">
        <div class="ui three column grid center aligned">
                <div class="column">
                    <div class="ui buttons icon">
                        <div class="ui button small">
                            <i class="icon plus"></i>
                        </div>
                    </div>
                </div>
                <div class="column">
                    <div class="ui labels circular">
                        <div class="ui label">
                            124124
                        </div>
                    </div>
                </div>
                <div class="column">
                    <div class="ui buttons icon">
                        <div class="ui button small">
                            <i class="icon minus"></i>
                        </div>
                    </div>
                </div>
        </div>
        <div class="ui grid center aligned">
            <div class="row">
                <div class="column">
                    <h1>yo</h1>
                </div>
            </div>
            <div class="row">
                <div class="column">
                    <div class="ui segment" data-bind="foreach: {data: stories.strings, as: 'string'}">
                        <p data-bind="text: string"></p>
                    </div>
                </div>
            </div>
        </div>
    </div>
  </div>
</div>


还有我的带有viewModel的js文件

define(['knockout', 'dataContext'], function (ko, dataContext) {

viewModel = {
    activate: activate,
    main: ko.observable(true),
    stories: ko.observableArray([]),
};

return viewModel;

function activate() {
    return dataContext.getStories().then(function(data) {
        console.log(data.results);
        _.each(data.results, function(result) {
            console.log(result.strings);
            viewModel.stories.push({strings: result.strings});
        });
        console.log(viewModel.stories());
    });
  }
})


因此,foreach:“故事”不起作用,这就是问题。控制台告诉我

"Unable to process binding "foreach: function (){return stories }"
Message: Unable to process binding "foreach: function (){return {data:stories.strings,as:'string'} }"
Message: stories is not defined;"

最佳答案

由于第二个foreach引发了异常:

<div class="ui segment" data-bind="foreach: {data: stories.strings, as: 'string'}">
    <p data-bind="text: string"></p>
</div>


因为您处于“故事”的上下文中,所以编写stories.strings引发,因为stories项内没有stories属性,因此您只需要编写strings即可:

<div class="ui segment" data-bind="foreach: { data: strings, as: 'string' }">
    <p data-bind="text: string"></p>
</div>

09-27 09:47