gpt4 book ai didi

javascript - 通过 jQuery 添加 ng-style 属性, Angular 不更新

转载 作者:行者123 更新时间:2023-11-29 14:48:34 24 4
gpt4 key购买 nike

这里有一个 plunker 演示了这个问题:http://plnkr.co/edit/1ceWH9o2WNVnUUoWE6Gm

代码:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
console.log('yeah');
var header = $('#weird');
console.log(header);
header.attr("ng-style", "{'background-color' : 'red'}")
});

它添加了 ng-style 属性,但 angular 不知道它,所以它从未被应用。

这是我正在尝试做的事情的简化版本,我正在尝试向 chessboard.js 生成的棋盘中的每个方格添加一个 ng-style 属性.我这样做是通过将 ng-style 属性添加到编译函数内的每个方 block ,就像我将 ng-style 属性添加到标题中一样。如果有更好的方法来做到这一点,我很想知道。如果没有,我怎样才能在添加 ng-style 属性时更新 Angular ?

我已经阅读了有关 $scope$digest$apply 的内容,并且尝试过使用它们,但是还没弄清楚。实现此目标的最佳方法是什么?

最佳答案

这取决于指令的具体工作方式,但在 ngStyle 的情况下,您可能需要重新编译一个元素:

app.controller('myCtrl', function($scope, $compile) {
console.log('yeah');
var header = $('#weird');
console.log(header);
header.attr("ng-style", "{'background-color' : 'red'}");
$compile(header)($scope);
});

$apply 通常在 Angular 与纯 JS/jQuery 混合使用时提出,但只有当作用域绑定(bind)需要更新时才有意义,事实并非如此。此外,当异步回调发生时,它是有意义的,但是在 Controller 构造函数期间发生的范围变化被应用(没有魔法可以区分 Angular 和非 Angular 东西,所以如果你触发,就会出现“$apply already in progress”不需要时的摘要)。

我假设您是有意使用 jQuery,我可以免除您“angular-hates-jquery-selectors-bad-bad-you-re-doing-it-wrong”的单调乏味。

关于javascript - 通过 jQuery 添加 ng-style 属性, Angular 不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29481804/

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