Luis Martinez Luis Martinez - 6 months ago 16
AngularJS Question

evaluating scope object with a element attribute in AngularJS

I'm learning AngularJs. I following this example with a few modification and i dont get it why it does not work.

The example is as follow:

<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>




I hope you can help me with this little thing

Answer

Try like this with scope.data.day in your angular directive:

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);
            
<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>

Comments