首页 > 解决方案 > 更改 AngularJS 属性会更改 HTML 属性的值

问题描述

我有一个带有代码的base.html页面

<html lang="en" data-ng-app="MyApp" data-ng-controller="MyController">
<body style="background-color: [[ BackgroundPrimaryColor ]]">
.
.
.
{{ block content }}
{{ endblock }}
.
.
.
</body>
<script>
// Creating an AngularJS Module for our AngularJS Application
var app=angular.module("MyApp",[]);

// Changing syntax for AngularJS Expression
app.config(function($interpolateProvider) {
  $interpolateProvider.startSymbol('[[');
  $interpolateProvider.endSymbol(']]');
});

// Defining AngularJS Controller for our AngularJS Application
app.controller("MyController",function($scope){
    // Defining AngularJS Application Property to specify Mode of the Website
    $scope.DarkMode=false;

    // Defining function to change Mode of the Website
    $scope.changeDarkLightMode=function(){
        // Changing other values
        if ($scope.DarkMode){
            $scope.BackgroundPrimaryColor="black";
        }
        else{
            $scope.BackgroundPrimaryColor="white";
        }

        // Changing value of the property DarkMode
        $scope.DarkMode=!$scope.DarkMode;

    };
    
    // Calling changeDarkLightMode() whenever page loads
    $scope.changeDarkLightMode();

});
</script>
</html>

我有另一个页面名称联系 me.html与代码

{{ block content }}
<body onload="onLoad()">
.
.
.
</body>
<script>
function onLoad(){
 document.getElementsbyTagName("body")[0].setAttribute("style","background-repeat: no-repeat;background-attachment: scroll;background-image: url({% static 'Contact_Me_Image.png' %});background-size:cover;background-position: 0% 20%;");}
</script>
{{ endblock }}

因此,contact me.html页面构成了base.html的一部分。

联系 me.html页面中,我设置了from标记的style属性,以便从body<script>body

<body style="background-color: [[ BackgroundPrimaryColor ]]">
...
</body>

<body style="background-repeat: no-repeat;background-attachment: scroll;background-image: url({% static 'Contact_Me_Image.png' %});background-size:cover;background-position: 0% 20%;">
...
</body>

在我更改 AngularJS Property 的值之前,一切正常BackgroundPrimaryColor。一旦我更改了 AngularJS Property 的值BackgroundPrimaryColor,就会body再次从

<body style="background-repeat: no-repeat;background-attachment: scroll;background-image: url({% static 'Contact_Me_Image.png' %});background-size:cover;background-position: 0% 20%;">
...
</body>

<body style="background-color: [[ BackgroundPrimaryColor ]]">
...
</body>

所以谁能说出为什么改变 AngularJS 属性的BackgroundPrimaryColor值会改变.stylebody

标签: javascripthtmlcssangularjs

解决方案


请删除自定义 “[[”插值,这可以通过使用“{{”默认标签来实现

<body style="background-color: {{BackgroundPrimaryColor}}">
...
</body>

并在控制器中使用它

app.controller("MyController",function($scope){

$scope.BackgroundPrimaryColor="#FFF";

$scope.init=function(){
    $scope.BackgroundPrimaryColor="red";
}

$scope.init();

});

推荐阅读