使用AngularJS中的元素属性评估范围对象

时间:2016-05-23 15:11:13

标签: javascript arrays angularjs if-statement

我正在学习AngularJs。我通过一些修改来关注这个例子,我不知道为什么它不起作用。

示例如下:

<html ng-app="app">
<head>
    <title>Calendar</title>
    <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <script src="angular.min.js"></script>
    <script>
        angular.module('app', [])
                .controller('dayCtrl', dayCtrl)
                .directive('highlight', highlight);

        function dayCtrl ($scope){
            var daysName = ['Sunday', 'Monday', 'Tuesday'];
            $scope.data = {
                day : daysName[new Date().getDay()],
                tomorrow : daysName[(new Date().getDay() + 1)]
            };
        }

        function highlight () {
            return function (scope, element, attrs){
                if(scope.day == attrs['highlight']){
                   element.css('color', 'red');
                }
            }
        }
    </script>
</head>
<body>
    <div class="container">
        <div class="row panel" ng-controller="dayCtrl">
            <div class="col-sm-12 page-header clearfix">
                <h4>Angular App</h4>
            </div>
            <h4 highlight="Monday">
                Today is {{ data.day || 'unknown'}}
            </h4>
            <h4>
                Tomorrow is {{ data.tomorrow || 'unknown' }}
            </h4>
        </div>
    </div>
</body>

我希望你能用这个小东西来帮助我

1 个答案:

答案 0 :(得分:1)

在角度directive中使用scope.data.day尝试这样做:

&#13;
&#13;
function dayCtrl($scope) {
    var daysName = ['Sunday', 'Monday', 'Tuesday'];
    $scope.data = {
        day: daysName[new Date().getDay()],
        tomorrow: daysName[(new Date().getDay() + 1)]
    };
}

function highlight() {
    return function(scope, element, attrs) {
        if (scope.data.day == attrs['highlight']) {
            element.css('color', 'red');
        }
    }
}

angular.module('app', [])
    .controller('dayCtrl', dayCtrl)
    .directive('highlight', highlight);
            
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app">
    <div class="row panel" ng-controller="dayCtrl">
            <div class="col-sm-12 page-header clearfix">
                <h4>Angular App</h4>
            </div>
            <h4 highlight="Monday">
                Today is {{ data.day || 'unknown'}}
            </h4>
            <h4>
                Tomorrow is {{ data.tomorrow || 'unknown' }}
            </h4>
        </div>
  </div>
&#13;
&#13;
&#13;