Reputation: 2385
I'm trying to use AngularJS to create a simple click to bold effect. I hope not to involve any controller scripts, but included or not, my code just don't work.
My HTML code with angular markup
<div ng-app="organHome">
<dl class="sub-nav" ng-controller="inModalSwitchCtrl">
<dd ng-class="content:bold"><a ng-click="switchContent()" ng-model="content">Contents</a>
</dd>
<dd ng-class="comment:bold"><a ng-model="comment" ng-click="switchComment()">Comments</a>
</dd>
</dl>
</div>
My js code:
angular.module('organHome', [])
.controller('inModalSwitchCtrl', function ($scope) {
$scope.content = true;
$scope.comment = false;
$scope.switchContent = function ($scope) {
$scope.content = true;
$scope.comment = false;
};
$scope.switchComment = function ($scope) {
$scope.comment = true;
$scope.content = false;
};
});
Here is the example on fiddle
I know it must be very rookie-ish, but I'm stuck. Any help?
My original goal was to minimize my code, and hopefully no controller.js at all.
If there is anyway to just do it with existing directives, I would love to follow!
My horrible and not working approach looks like this:
<dl class="sub-nav">
<dd ng-class="'active':content"><a ng-click="content = true" ng-model="content">Contents</a></dd>
<dd ng-class="'active':comment"><a ng-model="comment">Comments</a></dd>
</dl>
Upvotes: 0
Views: 7743
Reputation: 4870
in html:
<dd ng-class="{'bold':content}"><a ng-click="switchContent()" ng-model="content">Contents</a></dd>
<dd ng-class="{'bold':comment}"><a ng-model="comment" ng-click="switchComment()">Comments</a></dd>
Also Add css :
.bold {font-weight: bold}
EDIT
For less code, you can use this :
<div ng-app="organHome">
<dl class="sub-nav" ng-controller="inModalSwitchCtrl" ng-init="content=true">
<dd ng-class="{'bold':content}"><a ng-click="content=true">Contents</a></dd>
<dd ng-class="{'bold': !comment}"><a ng-click="content=false">Comments</a></dd>
</dl>
</div>
Upvotes: 2
Reputation: 11718
Simplified syntax for ng-class is {value:expression} So your code would look like this:
<dd ng-class="{bold:content}"><a ng-click="switchContent()" ng-model="content">Contents</a></dd>
<dd ng-class="{bold:comment}"><a ng-model="comment" ng-click="switchComment()">Comments</a></dd>
Also you should select "No wrap in head". In your case angular did not even started.
Here is the working fiddle - http://jsfiddle.net/qHkWA/3/
Also for better understanding of how this work you may take a look at this thread - What is the best way to conditionally apply a class?
And I don't know is it suits your purposes but you may simplify whole your code using jquery's toggleClass - http://jsfiddle.net/8kgMZ/3/ :
<dd class="bold"><a ng-click="toggleBold()">Contents</a></dd>
<dd><a ng-click="toggleBold()">Comments</a></dd>
and the controller:
.controller('inModalSwitchCtrl', function ($scope) {
$scope.toggleBold = function() {
angular.element(document).find('dd').toggleClass('bold');
};
Upvotes: 0