Angularjs show hide css issue - javascript

I had a hard issue figuring out on how to hide and show icon/text with angular code. I am completely new to angular and tried hard on the below fiddle code. How do I hide + or minus icon with .closest in such dom scenarios.
<div ng-controller="MyCtrl">
{{name}}
<div data-toggle="collapse" aria-expanded="true" data-target="#list-item-line-0" id="expandCollapseChild" ng-click="addExpandCollapseChildIcon()">
<div>
<div>
<label>
<div>
<span class="icon-expand">-</span>
<span class="icon-collapse">+</span>
</div>
<div>
Click me to hide minus icon
</div>
</label>
</div>
</div>
</div>
</div>
var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.name = 'Superhero';
$scope.addExpandCollapseChildIcon = function() {
alert('');
if (angular.element('#expandCollapseChild').hasClass('collapsed')) {
angular.element(this).closest('.icon-collapse').css('display', 'none');
} else {
if (angular.element('#expandCollapseChild').hasClass('collapsed')) {
angular.element(this).closest('.icon-collapse').css('display', 'block');
}
}
}

In Angular, this is the wrong approach. You shouldn't actually show or hide elements inside the controller. That's applying a jQuery style (working directly on the DOM) to Angular.
In Angular, you'd use something like ng-if, ng-show or ng-class, all of which can link back to a property on the scope object that is accessible via the controller.
Here are some examples:
<div ng-if="myProp === 'ShowMe'">
<div ng-show="myProp === 'ShowMe'">
<div ng-class="{myCssClass: myProp === 'ShowMe'">
Inside your controller, you'd have something like this:
function MyCtrl($scope) {
$scope.myProp = 'ShowMe';
$scope.addExpandCollapseChildIcon = function(newPropValue) {
$scope.myProp = newPropValue;
}
}
Here's some links to documentation on ng-if, ng-show and ng-class:
https://docs.angularjs.org/api/ng/directive/ngIf
https://docs.angularjs.org/api/ng/directive/ngShow
https://docs.angularjs.org/api/ng/directive/ngClass

AngularJS has a bunch of angulary ways of doing things, your question for example might look like this:
var app = angular.module("app", []);
app.controller("ctrl", function($scope) {
$scope.collapsed = true;
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="ctrl">
<span ng-bind="collapsed ? '+' : '-'"></span>
</div>
</div>
It watches a model and changes it's appearance based on that model using the ternary operator within ng-bind.

The way you defined your app and controller was incorrect. There's a bunch of different ways to do this as you can see from the answers.
I took this approach:
<div ng-app='myApp' ng-controller="MyCtrl">
{{name}}
<div>
<div>
<div>
<label>
<div>
<span ng-show='(collapsed != false)' class="icon-expand">-</span>
<span ng-show='(collapsed == false)' class="icon-collapse">+</span>
</div>
<div ng-click='collapsed = !collapsed'>
Click me to hide minus icon
</div>
</label>
</div>
</div>
</div>
</div>
<script>
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function ($scope) {
$scope.name = 'Superhero';
$scope.collapsed = false;
});
</script>
Create a scoped variable that indicated whether or not it is collapsed . Then change that variable and the ng-shows will react.

Related

Can't append divs when using ng-switch-when AngularJS?

I am using ng-switch when method to append divs. This is the code created
<input type="checkbox" ng-model="data" />
<ng-switch on="data">
<span ng-switch-when="true">
<div class="firstSwitch"></div>
</span>
<span ng-switch-default>
<div class="secondSwitch"></div>
</span>
</ng-switch>
Its working fine now. But when i want to append something in the div.
Say, i want to append text using javascript inside secondSwitch div, but i can't append it because initially the secondSwitch div is not appended.
setTimeout(function(){
$(".secondSwitch").html("<p>Second Switch is displayed</p>");
$(".firstSwitch").html("<p>First Switch is displayed</p>");
},100);
Here the text is appended properly inside firstSwitch div because initially it is created but the text is not appended inside secondSwitch div because it's not created.
So, i can't append inside that div. So, how to overcome this problem guys. Here is the Plnkr
As you already noticed ng-switch modifies DOM and firstSwitch is not created initially. You should use binding to get this working. Here is working demo
<ng-switch on="data">
<span ng-switch-when="true">
<div class="firstSwitch"><p>{{firstText}}<p></div>
</span>
<span ng-switch-default>
<div class="secondSwitch"><p>{{secondText}}<p></div>
</span>
app.controller('MainCtrl', function($scope, $timeout) {
$scope.data = false;
$timeout(function(){
$scope.firstText = "First Switch is displayed";
$scope.secondText = "Second Switch is displayed";
},100);
Update
And here's demo for binding to html
Try this
<div class="secondSwitch"><div id="replacediv"></div></div>
var divElement = angular.element(document.querySelector('#replacediv'));
var appendHtml = $compile('<div>test</div>')($scope);
divElement.append(appendHtml);
you can use ng-show directive for this.
// Code goes here
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope,$timeout) {
$scope.data = false;
$scope.show = false;
$scope.change = function(){
$timeout(function(){
$scope.show = !$scope.show;
},300);
}
});
<script src="http://code.jquery.com/jquery-1.12.2.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="plunker">
<div ng-controller="MainCtrl">
<input type="checkbox" ng-model="data" ng-change="change()" />
Check
<ng-switch on="data">
<span ng-switch-when="true">
<div class="firstSwitch">
<p ng-show="show">First Switch is displayed</p>
</div>
</span>
<span ng-switch-default>
<div class="secondSwitch">
<p ng-show="!show">Second Switch is displayed</p>
</div>
</span>
</ng-switch>
</div>

How do I access this scope variable inside of isolated scope directive?

This is my situation in psuedo code
<div data-ng-controller="test">
<div isolated-directive>
<select ng-model="testControllerScopeVar">...</select>
</div>
<div ng-if="some condition that uses testControllerScopeVar"></div>
</div>
This worked perfectly before I added isolated-directive, now that it is added (scope: true) the ng-if no longer works because I think it is getting eat up inside of the directive.
What is the most efficient way to get this working without touching the structure of the html and isolated-directive?
Well it seems once I know the solution, it is so simple
<div data-ng-controller="test as testCtrl">
<div isolated-directive>
<select ng-model="testCtrl.testControllerScopeVar">...</select>
</div>
<div ng-if="testCtrl.testControllerScopeVar == 'whatever'"></div>
</div>
ControllerAs allows me to specifically access the right scope and works perfectly, thanks all for your time and input
One approach is to map the controller variable into your isolated scope and attach the isolated scope variable to your internal ng-model.
So your HTML would look like this:
<div data-ng-controller="test">
<div isolated-directive="testControllerScopeVar">
<select ng-model="isolatedScopeVar">...</select>
</div>
<div ng-if="some condition that uses testControllerScopeVar"></div>
</div>
And your directive declaration would look like this:
app.directive('isolatedDirective', function () {
return {
scope: {
isolatedScopeVar: '=isolatedDirective'
}
};
});
You can try jQuery to get the value and assign it to a new scope variable. Something like this
HTML
<div ng-app="TestApp">
<div data-ng-controller="test">
<div isolated-directive>
<input id="isolatedVar" ng-model="testControllerScopeVar" />
</div>
<div>
{{isolatedVar}}
</div>
</div>
</div>
JS
var app = angular.module('TestApp', []);
app.controller('test', function($scope) {
var element = angular.element(document.querySelector('#isolatedVar'));
element.bind('keyup', function() {
$scope.isolatedVar = element.val();
console.log($scope.isolatedVar);
$scope.$watch('isolatedVar', function() {});
});
});
app.directive('isolatedDirective', function() {
return {
scope: true
};
});
Working fiddle https://jsfiddle.net/kavinio/yzb8ouzd/1/

How to break data-binding after first rendering in Angular?

I've got a page in my website in which I want to show a checkbox. I only want to show the checkbox if the model is initially false. So I wrote this (this was my initial code, but it was a simplified version of what I have myself. I updated the code in the snippet at the end of this question to show the problem):
<div ng-if="!the_field">
<input ng-model="the_field" type="checkbox">
</div>
The problem is that if I click the checkbox, it disappears. That of course makes sense, but I have no idea how to solve this.
So what I basically want is to show the checkbox if the model was false upon rendering the HTML. But after that I want to somehow break the databinding so that the checkbox remains on the page even if the model changes to true.
Does anybody know how I can achieve this? All tips are welcome!
[EDIT]
I would prefer doing this from within the template, so that I don't get a double list of these fields (because I've got about 50 of them). Any ideas?
[EDIT 2]
Turns out that it did work with the example above, which was a simplified version of my own code. In my own code however, I'm not using simple a field, but an item in a dict. I updated the code above and made a snippet below to show the problem:
var MainController = function($scope){
$scope.the_field = {};
$scope.the_field.item = false;
};
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="" ng-controller="MainController">
parent: {{the_field.item}}
<div ng-if="!the_field.item">
child: {{the_field.item}}<br>
<input ng-model="the_field.item" type="checkbox">
</div>
</div>
You can clone the source object. Like this:
angular.module('app', []).
controller('ctrl', function($scope) {
$scope.the_field = false;
$scope.the_field_clone = angular.copy($scope.the_field);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
{{the_field}}
<div ng-if="!the_field_clone">
<input ng-model="$parent.the_field" type="checkbox">
</div>
</div>
http://jsbin.com/ditoka/edit?html,js
Update - option 2 - Directive
angular.module('app', []).
controller('ctrl', function($scope) {
$scope.the_field = false;
}).
directive('customIf', function() {
return {
scope: {
customIf: '='
},
link: function(scope, element, attrs) {
if (!scope.customIf) {
element.remove();
}
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
{{the_field}}
<div custom-if="!the_field">
<input ng-model="the_field" type="checkbox">
</div>
</div>
It works with the code of your question, try it out ;)
(see What are Scopes?)
var MainController = function($scope){
$scope.the_field = false;
};
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="" ng-controller="MainController">
parent: {{the_field}}
<div ng-if="!the_field">
child: {{the_field}}<br>
<input ng-model="the_field" type="checkbox">
</div>
</div>
The answer to your updated question:
You can use another property in your model, edited when the first click occurs...
var MainController = function($scope){
$scope.model = {init: true, the_field: false};
};
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="" ng-controller="MainController">
parent: {{model.the_field}}
<div ng-if="!model.the_field || !model.init">
<input ng-model="model.the_field" type="checkbox" ng-click="model.init=false;">
</div>
</div>

how to assign array element value to ng-click in angular js

In my program I have an Array which consists of header name and function name.
I am using ng-repeat in a div which consists of a span tag. I want to add different functionality for each iterated span so I stored function name in array.
my html code is:
<div ng-repeat="header in header" ng-init="head=header">
<h4 class="headers">{{ header.name}}</h4>
<div class="arrow-up" ng-show={{ header.arrowup}} ng-click={{header.close}}> </div>
</div>
my angular code is:
$scope.header=[{"name":"Subsection Header #1","arrowup":"arrowup","close":"close()"}];
$scope.close = function() {
console.log(hello);
};
I want to assign close() to the ng-click and arrowup to ng-show. How can I assign them to ng-click and ng-show
change:
<div class="arrow-up" ng-show={{ header.arrowup}} ng-click={{header.close}}>
To:
<div class="arrow-up" ng-show="header.arrowup" ng-click="this[header.close]()">
<button>
CLOSE ME
</button>
</div>
DEMO= http://jsfiddle.net/Lvc0u55v/1788/
ng-click is the problem as i see,
<div class="arrow-up" ng-show="header.arrowup" ng-click="header.close"></div>
we need not give {{}} to ng-click and ng-show.
hope it helps.
First you need to pass a real functions to array:
function arrowUp(){
// ng-show needs to receive true or false
return true;
}
function close(){
// do something here
}
$scope.headers=[{"name":"Subsection Header #1","arrowup":arrowUp,"close":close}];
The bind them in a view:
<div ng-repeat="header in headers">
<h4 class="header">{{ header.name}}</h4>
<div class="arrow-up" ng-show="header.arrowup()" ng-click="header.close()"> </div>
</div>
You need to use the $eval method, you can read more about it here
$scope.$eval Executes the expression on the current scope and returns the result. Any exceptions in the expression are propagated (uncaught). This is useful when evaluating Angular expressions
HTML:
<div ng-controller="TestController">
<div ng-repeat="header in headers">
<h4>{{ header.name}}</h4>
<button type="button" ng-click="onExecuteFunctionFromString(header.close)">Click Here</button>
</div>
</div>
JS:
var myApp = angular.module('myApp', []);
myApp.controller('TestController', ['$scope', function($scope) {
$scope.headers = [{
"name": "Subsection Header #1",
"arrowup": "arrowup",
"close": "close()"
}];
$scope.close = function() {
console.log('hello');
};
$scope.onExecuteFunctionFromString = function(stringFunction) {
$scope.$eval(stringFunction)
};
}]);
Please see working example here

unbind ng-click dynamically from element : angularjs

i have an element which have ng-click event and on clicking it adds a div that works fine. what i want is to remove ng-click after adding the div .
one way is to use ng-if
<div ng-click="addDiv()" ng-if="!divAdded" >
<span>i add a div</span>
</div>
<div class="disabled" ng-if="divAdded" >
<span>i add a div</span>
</div>
for this i have to add multiple div for single element that works on and off.
is there any way to unbind click event like we do in jquery dynamically?
any help will be appreciated
You can also do this:
<div ng-click="divAdded || addDiv()" >
<span>i add a div</span>
</div>
This will prevent ng-click from calling addDiv() if divAdded is true
Put that logic into the controller, not into the view
Controller:
(function(){
function divAddController() {
var self = this;
self.divAdded = false;
self.addDiv = function() {
if(!divAdded) {
//Add div here
self.divAdded = true;
}
}
}
angular.module("example")
.controller("divAddController", divAddController);
})();
View:
<div ng-controller="divAddController as divAdder">
<div ng-click="divAdder.addDiv()" ng-class="{disabled: divAdder.divAdded}">
<span>i add a div</span>
</div>
</div>
You can do it in a more easy way like this:
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function($scope) {
$scope.showDiv = false;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<button ng-click="showDiv = true;">I show the div</button>
<div ng-if="showDiv">I am visible!</div>
</div>

Categories