gpt4 book ai didi

javascript - AngularJS 指令在使用隔离范围时不将值插入模板

转载 作者:行者123 更新时间:2023-11-30 17:18:25 24 4
gpt4 key购买 nike

给定以下指令:

angular.module('news.directives', [])
.directive('newsArticle', function($location, $timeout) {
return {
restrict: 'AE',
replace: 'true',
templateUrl: 'partials/pages/news/directives/article.html',
scope: true
};
});

以及以下模板:

<div id="story-{{item.id}}" ng-class="{'red': item.active, 'story-container': true}">
<div class="story-banner-image"></div>
<div class="story stationary">{{ item.title | words: 10 }}</div>
<div class="story-banner-content"></div>
</div>

以及对指令的以下调用:

<news-article ng-repeat="item in news">
</news-article>

这行得通。但是如果我想使用一个独立的作用域并公开一个项目:

scope: {
item: '@'
}

// or

scope: {
news: '@'
}

// or

scope: {}

然后就不行了。模板中指定的所有 {{item.property}} 标签都返回空值(空字符串)。为什么 item 不存在于隔离范围内?

最佳答案

It's quite clearly inheriting it's parent properties when scope is set to true, but it's not inheriting when I tell it what it should inherit.

你的问题是你对 scope 配置的设置方式感到困惑。为了设置具有隔离范围的双向数据绑定(bind),您应该在 HTML 中提供相应的属性:

<news-article ng-repeat="item in news" item="item"></news-article>

然后相应地设置指令:

scope: {
item: '='
}

演示:http://plnkr.co/edit/b1I8PIc27MvjVeQaCDON?p=preview

关于javascript - AngularJS 指令在使用隔离范围时不将值插入模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25645229/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com