可以通过使用 ng-attribute 指令来使 AngularJS 属性的值同步更新到 HTML 属性中,示例代码如下:
HTML 代码:
{{btnStyle}}
AngularJS 代码:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.btnText = 'Change Color';
$scope.btnStyle = 'background-color: blue';
$scope.changeColor = function() {
if ($scope.btnStyle === 'background-color: blue') {
$scope.btnStyle = 'background-color: red';
} else {
$scope.btnStyle = 'background-color: blue';
}
};
});
ng-attribute 指令将模型绑定到特定的 HTML 属性(这里是 style 属性),这使得 AngularJS 可以更新该属性的值。在上面的示例中,当单击按钮时,控制器中的 changeColor 函数将更改 $scope.btnStyle 的值,从而更改按钮样式的背景颜色。在 HTML 中,ng-attribute 将新的样式值同步更新到按钮的 style 属性中,同时在 div 中显示新的样式字符串。