I have the following code.
html:
<div ng-controller="Test">
<div ng-click="first()" ng-hide="seconddiv">First
<div ng-click="second()" ng-show="seconddiv">Second</div>
</div>
</div>
js:
var app = angular.module('app',[]);
app.controller('Test',function($scope){
$scope.first = function(){
alert("first clicked");
}
$scope.second = function(){
alert("second clicked");
}
});
On executing the above code:
a). I should see only First
by default(I can see one now: First
) - it is fine now
b). then, if I click on First
, then it should execute it's first()
method, then First
should be replaced with Second(on UI)
- it's not coming
c). then, if I click on Second
, then it should execute it's second()
method only, (it should not execute any other methods like first()
except second()
method) - it's not coming
I request you to please help me regarding this that how can we do this? Thanks in advance!
Please note that Html <div>
structure should not change, so it should be same.
Created Fiddle .
Go the Angular Way.
You will have just one function, toggle
. Which will toggle the value of variable first
from true to false and vice versa.
Depending on value of first
you will show either div with content as First
or that with content as Second
.
You will also refactor your HTML a bit as follows
<div ng-controller="Test">
<div ng-if="first" ng-click="toggle()">First</div>
<div ng-if="!first"ng-click="toggle()">Second</div>
</div>
And in your JS you will do
var app = angular.module('app',[]);
app.controller('Test',function($scope){
$scope.first = true;
$scope.toggle = function(){
$scope.first = !$scope.first;
}
});
==== EDIT:
Alternatively, you don't even need the toggle
function. Just use ng-click
expression.
<div ng-controller="Test">
<div ng-if="first" ng-click="first=!first">First</div>
<div ng-if="!first"ng-click="first=!first">Second</div>
</div>
And in JS
app.controller('Test',function($scope){
$scope.first = true;
});