gpt4 book ai didi

javascript - ng 类不响应 Angular 中模型的变化?

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

经过广泛搜索,从A ternary in templates 得到了一些帮助并获得部分功能性结果,我 99% 确定我做对了 99%,但是......显然不完全,所以我来了。

基本的 HTML 结构:

<ul>
<li class="week-row" ng-repeat="week in weeks" id="{{$index}}">
<ul class="tiles" ng-class="{ 'expanded': week.isOpen, 'hidden': !week.isOpen }">
<li class="day-tile"
ng-class="{'active': (activeDay == $parent.$index + '-' + $index) }"
id="{{$parent.$index + '-' + $index}}"
ng-repeat="day in week.days"
ng-click="fn2({ week: $parent.$index, day: $index })">

<!-- moved ng-class to here, and it works? -->
<div>some stuff in here</div>

</li>
</ul>
</li>
</ul>

位于其上方的 Controller 中的内容:

$scope.activeDay = null;

$scope.fn1 = function() { $scope.activeDay = '0-0'; }; // this works, and sets the first one active

$scope.fn2 = function(data) { $scope.activeDay = data.week + '-' + data.day; }; // this sets the first one not active, but none of the others go active

我正在尝试使用 $parent.$index 根据其在嵌套数组中的索引将嵌套列表项之一设置为事件状态和 $index作为字符串,由“-”连接。

让我失望的是 console.logging $scope.activeDay , data.week + '-' + data.day , 和两者 =====比较结果完全符合我的预期,(the same strings, true, true)当我将 activeDay 设置为“0-0”时它在初始加载时工作,所以我显然在我的绑定(bind)中丢失了一些东西或者......?

找到这个之后:https://egghead.io/lessons/angularjs-the-dot - 我尝试将其设置为一个对象,这样我就无法进入一些奇怪的隔离范围废话:$scope.tiles = { activeDay: null };然后从我的函数中设置该属性,但无济于事。

为什么最初设置它有效,而后来更改它却不起作用?这是类的不正确绑定(bind)还是...?

我也试过

class="day-tile {{activeDay == $parent.$index + '-' + $index ? 'active' : ''}}"

这最初有效,但之后就坏了......

非常感谢您的帮助!

更新:

搬家后ng-class="{'active': (activeDay == $parent.$index + '-' + $index) }"ng-repeat 内的 div 上编辑.day-tile li,它工作正常。

知道为什么会这样吗?

最佳答案

根据您提供的信息,我可以正常工作 jsFiddle .

我删除了您硬编码为 true 的类,并将它们固定在 class="" 中。您为我输入的表达式评估的类 ng-class=""

我将您的函数附加到 $scope 以便 ng-click 可以找到它们。所以 $scope.fn2 而不是 var fn2。

在不知道更多细节的情况下,我会说这应该可以解决您的问题。

代码更改:

Controller :

$scope.activeDay = null;

$scope.fn1 = function() { $scope.activeDay = '0-0'; };

$scope.fn2 = function(data) { $scope.activeDay = data.week + '-' + data.day; };

部分:

    <ul class="tiles" ng-class="{'expanded' : week.isOpen, 'hidden' : !week.isOpen}">
<li class="day-title"
ng-class="{'active': (activeDay == $parent.$index + '-' + $index)}"
id="{{$parent.$index + '-' + $index}}"
ng-repeat="day in week.days"
ng-click="fn2({ week: $parent.$index, day: $index })">
//put expression here so you can see the list item
{{week.day}}
</li>
</ul>

关于javascript - ng 类不响应 Angular 中模型的变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27327299/

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