ng-class范围变量不起作用

时间:2017-05-14 07:08:04

标签: javascript html css angularjs

我正在尝试根据Angular JS中的范围变量添加CSS:

<html>
<head>
    <style type="text/css">
        body {color: black; font-size: 10px;}
        .redcolor {color: red; font-size: 20px}
        .greencolor {color: green; font-size: 100px}
    </style>
</head>
<body ng-app="app">
    <div ng-controler="controller">
        <span ng-class="{redcolor: test1.isRed, greencolor: test1.isGreen}">Span1</span><br/><br/>
        <span ng-class="{redcolor: test2.isRed, greencolor: test2.isGreen}">Span2</span>
    </div>

    <script src="angular.js"></script>
    <script type="text/javascript">
    angular.module('app',[])
    .controller('controler', function($scope) {
        $scope.test1 = {isRed: true, isGreen: false};
        $scope.test2 = {isRed: false, isGreen: true};
    });
    </script>
</body>
</html>

当我运行这个程序时,它只是应用了body的CSS。我需要带有redColor样式的span 1和带有greenColor样式的Span 2。

请帮助我解释此代码中的问题。

1 个答案:

答案 0 :(得分:2)

您的代码存在一些问题,

(i)应该 ng-controller 而不是ng-controler

(ii)您的控制器名称也是 controler 而非 controller

按如下方式更改,

 <div ng-controller="controler">    
 </div>

<强>样本

angular.module('app',[])
    .controller('controler', function($scope) {
        $scope.test1 = {isRed: true, isGreen: false};
        $scope.test2 = {isRed: false, isGreen: true};
    });
<html>
<head>   
 <style type="text/css">
        body {color: black; font-size: 10px;}
        .redcolor {color: red; font-size: 20px}
        .greencolor {color: green; font-size: 100px}
  </style>
</head>
<body ng-app="app">
    <div ng-controller="controler">
          <span ng-class="{redcolor: test1.isRed, greencolor: test1.isGreen}">Span1</span><br/><br/>
    <span ng-class="{redcolor: test2.isRed, greencolor: test2.isGreen}">Span2</span>

    </div>
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js"></script>  
</body>
</html>