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>
Related
I have a piece of code on which angularjs ng-message doesnot seem to work.
Here is a JSfiddle
<div ng-app="app" ng-controller="myctrl">
<form name="myform" novalidate>
error: {{myform.definition.$error}}
<textarea ng-blur="handleBlur(myform)"
name="definition"
ng-model="$ctrl.definition"
ng-blur="$ctrl.handleBlur(myform)">
</textarea>
<div ng-messages="myform.definition.$error">
<div ng-message="validationError">
Please enter a value for this field.
</div>
</div>
</form>
</div>
controller:
angular.module('app', []).controller('myctrl', function($scope) {
$scope.someval = true;
$scope.handleBlur = function(form) {
form.definition.$error.validationError = false;
$scope.someval = !$scope.someval
form.definition.$error['validationError'] = $scope.someval;
}
})
From the docs, https://docs.angularjs.org/api/ngMessages#dynamic-messaging
Feel free to use other structural directives such as ng-if and
ng-switch to further control what messages are active and when. Be
careful, if you place ng-message on the same element as these
structural directives, AngularJS may not be able to determine if a
message is active or not. Therefore it is best to place the ng-message
on a child element of the structural directive.
From:
<div ng-messages="myform.definition.$error">
<div ng-message="validationError">
Please enter a value for this field.
</div>
</div>
To:
<div ng-messages="myform.definition.$error">
<div ng-if="showRequiredError">
<div ng-message="validationError">
Please enter a value for this field.
</div>
</div>
</div>
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/
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.
I currently have this site - http://dev.5874.co.uk/scd-data/ where I have a dropdown which displays results from WP-API which I am pulling in through AngularJS.
It currently combines the two sets of results as they're separate URL's, the results are in categories within a custom post type so if both posts are 'tagged' in the same category chosen they display twice. I need a way to combine the two sets of results but only showing one of the posts - I hope this makes sense. I'm very new to API data and AngularJS and I imagine there is a much simpler way of doing this. Any help would be much appreciated. Here is a snippet of my code to show how it's currently working.
Thanks in advance!
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<style>
.desc {display: none;}
</style>
<script type="text/javascript">
$(function(){
$('.selectOption').change(function(){
var selected = $(this).find(':selected').text();
//alert(selected);
$(".desc").hide();
$('#' + selected).show();
}).change()
});
</script>
<script>
var app = angular.module('myApp', []);
app.controller('northWestCtrl', function($scope, $http) {
var url = 'http://scd.blaze.wpengine.com/wp-json/posts?type=listings&filter[listing_area]=northwest';
$http.get(url).then(function(data) {
$scope.data = data.data;
});
});
</script>
<select class="selectOption">
<option>Search by Region</option>
<option>NorthWest</option>
<option>NorthEast</option>
<option>Midlands</option>
<option>EastAnglia</option>
<option>SouthEast</option>
<option>SouthWest</option>
<option>Scotland</option>
<option>Wales</option>
<option>NorthernIreland</option>
<option>ChannelIslands</option>
</select>
<div id="changingArea">
<body ng-app="myApp">
<div id="NorthWest" class="desc">
<div ng-controller="northWestCtrl">
<div ng-repeat="d in data">
<h2 class="entry-title title-post">{{d.title}}</h2>
<img src="{{d.acf.logo}}">
<div id="listing-contact">Contact: {{d.acf.contact}}, {{d.acf.position}}</div>
<div id="listing-address-1">
{{d.acf.address_1}}, {{d.acf.address_2}} {{d.acf.address_3}} {{d.acf.town}} {{d.acf.county}} {{d.acf.postcode}}
</div>
<div id="listing-phone">Telephone: {{d.acf.telephone}}</div>
<div id="listing-mobile">Mobile: {{d.acf.mobile}}</div>
<div id="listing-email">Email: {{d.acf.email}}</div>
<div id="listing-website">Website: {{d.acf.website}}</div>
<div id="listing-established">Established: {{d.acf.established}}</div>
<div id="listing-about">About: {{d.acf.about}}</div>
<div id="listing-mailingaddress">Mailing Address: {{d.acf.mailing_address_}}, {{d.acf.mailing_address_2}}, {{d.acf.mailing_address_3}}, {{d.acf.mailing_town}}, {{d.acf.mailing_county}}, {{d.acf.mailing_postcode}}</div>
<div id="listing-directions">Directions: {{d.acf.directions}}</div>
<div id="scd-link">View on The Shooting Club Directory</div>
</div>
</div>
</div>
</body>
</div>
Here is a working code pen - http://codepen.io/anon/pen/yePYdq
Angular is a great JavaScript front-end framework to choose, and you're off to a good start, but a lot of changes could be made. I've made some suggested changes for easier ways to do things below.
See this CodePen for all changes.
It looks like you've grasped the idea of ng-repeat, but there's definitely a lot of repeated HTML and JS in your view and controller, so let's see if we can do better.
Let's try this without jQuery to avoid direct manipulation of the DOM. And instead of many controllers, we can do this with a single controller.
<div ng-app="MyApp">
<div ng-controller="MyController">
...
</div>
</div>
<script type="text/javascript">
var app = angular.module('MyApp', []);
app.controller('MyController', ...);
</script>
For the dropdown, we'll use ng-repeat in our view and display the names of the shooting types from our model
...
<select ng-model="selectedListing">
<option
ng-repeat="listingShootingType in listingShootingTypes"
value="{{listingShootingType.name}}">
{{listingShootingType.name}}
</option>
</select>
...
<script type="text/javascript">
...
// Our selections/filters
$scope.listingShootingTypes = [
'All',
'Air Rifle/Air Pistol',
'Clay',
'ABT',
'Double Trap',
'English Skeet',
'English Sporting',
'Fitasc',
'Olympic Skeet',
'Olympic Trap',
'Simulated Game',
'Sport Trap/Compact',
'Universal Trench',
'ZZ/Helice',
'Rifle',
'Centrefire Target Rifle',
'Gallery Rifle',
'Muzzle Loading',
'Practice Shotgun',
'Smallbore Rifle'
];
...
</script>
With only one controller, we can still use ng-repeat for each listing.
<div ng-repeat="d in data">
<h2 class="entry-title title-post">{{d.title}}</h2>
<div id="listing-image"><img src="{{d.acf.logo}}"></div>
<div id="listing-contact">Contact: {{d.acf.contact}}, {{d.acf.position}}</div>
<div id="listing-address-1">
{{d.acf.address_1}}, {{d.acf.address_2}} {{d.acf.address_3}} {{d.acf.town}} {{d.acf.county}} {{d.acf.postcode}}
</div>
<div id="listing-phone">Telephone: {{d.acf.telephone}}</div>
<div id="listing-mobile">Mobile: {{d.acf.mobile}}</div>
<div id="listing-email">Email: {{d.acf.email}}</div>
<div id="listing-website">Website: {{d.acf.website}}</div>
<div id="listing-established">Established: {{d.acf.established}}</div>
<div id="listing-about">About: {{d.acf.about}}</div>
<div id="listing-mailingaddress">Mailing Address: {{d.acf.mailing_address_}}, {{d.acf.mailing_address_2}}, {{d.acf.mailing_address_3}}, {{d.acf.mailing_town}}, {{d.acf.mailing_county}}, {{d.acf.mailing_postcode}}</div>
<div id="listing-directions">Directions: {{d.acf.directions}}</div>
<div id="scd-link">View on The Shooting Club Directory</div>
</div>
Finally... How do we only display listings that match our selected shooting type from the dropdown? We could use a custom Angular filter!
...
<div ng-repeat="d in data | filter:isSelectedListing">
...
<script type="text/javascript">
...
// Let's define a custom Angular filter because the WordPress JSON is complex
$scope.isSelectedListing = function(listing) {
// Show nothing if nothing is selected
if (angular.isUndefined($scope.selectedListing) || $scope.selectedListing == '') {
return false;
}
// Show all if 'All' is selected
if ($scope.selectedListing == 'All') {
return true;
}
// If the shooting type we're looking for is present, show the listing.
// To do this, we parse the WordPress JSON object model.
if (angular.isDefined(listing.terms.listing_shooting_type)) {
for (var i = 0; i < listing.terms.listing_shooting_type.length; i++) {
if (listing.terms.listing_shooting_type[i].name == $scope.selectedListing) {
return true;
}
}
}
return false;
};
...
</script>
Hopefully this gives you an idea of how we better leverage ng-repeat + DRY :)
The entire CodePen is here.
I have something similar to this:
<div ng-controller="ControllerA">
<input type="text" id="search_form" value="Search" ng-model="searchModel" />
</div>
<div ng-controller="ControllerB">
<ul>
<li ng-repeat="item in items | filter:searchModel">{{item}}</li>
</ul>
</div>
But when I search in the input bar, it does not impact my list. How can I make my model from one controller impact the content of another?
Thanks.
Edit
ControllerA and ControllerB are entirely isolated of each other and I would like to keep it that way. If I need to share the model with the other controller, how would I use $rootScope to do that?
You can use a service to share data between controllers.
Use the factory feature which angular has to define the service.
Here is an example which i found here with and easy google search.
<!doctype html>
<html ng-app="project">
<head>
<title>Angular: Service example</title>
<script src="http://code.angularjs.org/angular-1.0.1.js"></script>
<script>
var projectModule = angular.module('project',[]);
projectModule.factory('theService', function() {
return {
thing : {
x : 100
}
};
});
function FirstCtrl($scope, theService) {
$scope.thing = theService.thing;
$scope.name = "First Controller";
}
function SecondCtrl($scope, theService) {
$scope.someThing = theService.thing;
$scope.name = "Second Controller!";
}
</script>
</head>
<body>
<div ng-controller="FirstCtrl">
<h2>{{name}}</h2>
<input ng-model="thing.x"/>
</div>
<div ng-controller="SecondCtrl">
<h2>{{name}}</h2>
<input ng-model="someThing.x"/>
</div>
</body>
</html>
if you have a model that needs to be shared you should use a service that way both controller can access the data and be aware of any changes