AngularJS-ng-hide not working - javascript

I am trying to use ng-hide to display the action of "Edit" button. For this, I am using a boolean "edit" in this way: "ng-model="edit" ng-value="true", but it has no effect and I can't figure it out why.
Here is my code:
<!DOCTYPE html>
<html >
<head>
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<meta charset="UTF-8">
<script src="../../../bower_components/angular/angular.js"></script>
<script src="app.js"></script>
<script src="categories/module/category-module.js"></script>
<script src="categories/controller/category-controller.js"></script>
<script src="categories/service/category-service.js"></script>
<title>Categories</title>
</head>
<body><div lang="en" ng-app="myCategories">
<div ng-controller="categoryController">
<div class="w3-container" ng-init='getCategories()'>
<h3>Categories</h3>
<table class="w3-table w3-bordered w3-striped">
<tr>
<th>Edit</th>
<th>Name</th>
<th>Description</th>
</tr>
<tr ng-repeat="category in categories">
<td>
<button class="w3-btn w3-ripple" ng-click="editCategory(category.id) " ng-model="edit" ng-value="true">✎ Edit</button>
</td>
<td>{{category.name }}</td>
<td>{{ category.description }}</td>
</tr>
</table>
<form ng-hide="edit">
<h3 ng-hide="edit">Edit Category:</h3>
<label> Name:</label>
<input class="w3-input w3-border" type="text" ng-model="name" ng-disabled="!edit" placeholder="{{category.name}}">
<br>
<label>Description:</label>
<input class="w3-input w3-border" type="text" ng-model="description" ng-disabled="!edit" placeholder="{{category.description}}">
<br>
<label>New Description:</label>
<input class="w3-input w3-border" type="text" ng-model="newDescription" placeholder="New Description">
<br>
<button class="w3-btn w3-green w3-ripple" ng-disabled="error || incomplete">✔ Save Changes</button>
</form>
</div>
</div>
</div>
</body>
</html>
//app.js
(function() {
var myComments = angular.module('myComments', [ 'comment' ]);
var myCategories = angular.module('myCategories', [ 'category' ]);
var myTopics = angular.module('myTopics', [ 'topic' ]);
})();
//category-controller
(function() {
'use strict';
angular.module('category').controller('categoryController',
topicControllerFunction);
topicControllerFunction.$inject = [ '$scope', 'categoryService' ];
function topicControllerFunction($scope, categoryService) {
$scope.getCategories = getCategories;
function getCategories() {
console.log();
$scope.categories=[];
var promise=categoryService.getCategories();
promise.then(function(data){
if(data!=undefined && data!=null){
$scope.categories=data;
} else{
$scope.categories=undefined;
}
},function(error){
console.log('error='+error);
$scope.categories=undefined;
})
categoryService.getCategories();
$scope.categories = categoryService.getCategories();
}
}
}())

Make sure edit is set to true in the case where you want to hide the desired section.
Inside editCategory() looks like a a good place for this to happen, instead of ng-value=true
Set $scope.edit = true; in editCategory()

Do something like:
<span ng-show = "edit == true">

I'm not sure if it can be done the way you're attempting (I've never used that technique, but here's how I'd do it:
<button ng-click="edit=!edit" ... ></button>
If you need edit to be true on load, you could either set it in your controller (best), or use ng-init:
<button ng-click="edit=!edit" ng-init="edit=true" ... ></button>
Also, you should have a dot in your ng-model value: If you are not using a .(dot) in your AngularJS models you are doing it wrong?

Related

angular controller by module blank page

hello i have a problem with angular im benninger to this framework but i have some knowledge about it . Yesterday i faced a problem when i wanted to change controller from a global function(in this case all is OK) to controller by module i recive blank page here is my code
angular.module('myApp', ['ngRoute', 'membersService']).config(
['$httpProvider', '$routeProvider', function ($httpProvider, $routeProvider) {
$routeProvider.when('/home', {
templateUrl: 'partials/home.html',
controller: MembersCtrl
}).otherwise({
redirectTo: '/home'
});
}]);
var myApp = angular.module('myApp');
myApp.controller('MembersCtrl',['$scope','$http', 'MembersSrv',function ($scope, $http, MembersSrv) {
$scope.refresh = function () {
return MembersSrv.getAllPersons().then(function (data) {
$scope.persons = data.data;
});
};
$scope.clearMessages = function () {
$scope.successMessages = '';
$scope.errorMessages = '';
$scope.errors = {};
};
$scope.reset = function () {
if ($scope.regForm) {
$scope.regForm.$setPristine();
}
$scope.newPerson = {name: "", lname: "", phoneNumber: ""};
$scope.clearMessages();
};
$scope.register = function () {
$scope.clearMessages();
MembersSrv.save($scope.newPerson, function (data) {
$scope.refresh();
$scope.reset();
$scope.successMessages = ['Member Registered'];
}, function (result) {
if ((result.status == 409) || (result.status == 400)) {
$scope.errors = result.data;
} else {
$scope.errorMessages = ['Unknown server error'];
}
});
};
$scope.refresh();
$scope.reset();
$scope.orderBy = 'name';
}]);
angular.module('membersService', []).service('MembersSrv', [
'$http', function ($http) {
this.getAllPersons = function () {
var url = "http://localhost:8080/gadziksy-web/rest/person";
var req = {
method: 'GET',
url: url,
};
return $http(req);
}
}]);
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<title>myApp</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<!-- Disable phone number detection on iOS. -->
<meta name="format-detection" content="telephone=no"/>
<link rel="stylesheet" href="css/screen.css" type="text/css"/>
<!-- Load angularjs -->
<script src="js/libs/angular.js"></script>
<!-- Load angularjs-route, which allows us to use multiple views displayed through application routes -->
<script src="js/libs/angular-route.js"></script>
<!-- Load angularjs-resource, which allows us to interact with REST resources as high level services -->
<script src="js/libs/angular-resource.js"></script>
<!-- Load the controllers for our app -->
<script src="js/controllers/MemberCtrl.js"></script>
<!-- Load the application wide JS, such as route definitions -->
<script src="js/app.js"></script>
<!-- Load the services we have defined for the application, particularly the REST services -->
<script src="js/services/MemberSrv.js"></script>
</head>
<body>
<div ng-view></div>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<div ng-controller="MembersCtrl">
<h1 align="center">International Bank Application</h1>
<div>
<p>You have successfully connected to the Application.</p>
</div>
<form name="regForm" ng-submit="register()">
<h2>Member Registration</h2>
<fieldset>
<legend>Register a member:</legend>
<div>
<label for="name">Name:</label>
<input type="text" name="name" id="name" ng-model="newPerson.name" placeholder="Your Name" required
autofocus/>
</div>
<div>
<label for="lname">Lname:</label>
<input type="text" name="lname" id="lname" ng-model="newPerson.lname" placeholder="Your Lastname"
required/>
</div>
<div>
<label for="dob">Date</label>
<input type="date" name="dob" id="dob" ng-model="newPerson.dob" placeholder="Your Date" required/>
</div>
<ul ng-hide="!successMessages" class="success">
<li ng-repeat="message in successMessages">{{message}}</li>
</ul>
<ul ng-hide="!errorMessages" class="error">
<li ng-repeat="message in errorMessages">{{message}}</li>
</ul>
<div>
<input type="submit" ng-disabled="regForm.$invalid" id="register" value="Register"/>
<input type="button" ng-click="reset()" name="cancel"
id="cancel" value="Cancel"/>
</div>
</fieldset>
</form>
<h2>Persons</h2>
<em ng-show="persons.length == 0">No registered members.</em>
<table ng-hide="persons.length == 0" class="simpletablestyle">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Lname</th>
<th>Date</th>
<th>REST URL</th>
</tr>
</thead>
<tr ng-repeat="person in persons | orderBy:orderBy">
<td>{{person.id}}</td>
<td>{{person.name}}</td>
<td>{{person.lname}}</td>
<td>{{person.dob}}</td>
<td>details-{{person.id}}
</td>
</table>
<div>
REST URL for all members: /rest/members
</div>
<div>
<input type="button" ng-click="refresh()" name="refresh"
id="refresh" value="Refresh"/>
</div>
</div>
Change controller: MembersCtrl to controller: 'MembersCtrl' in $routeProvider config

How to put data in session in angular js

On my home screen ,I seacrh some data by calling angular controller(SeacrhController),then I click on a button(Start) on home page,which open another tab.On clicking done button on second tab,that second tab is closed and parent page is refreshed.
I want to have data searched earlier on my parent page.Can anyone please tell,how I can achieve this.How can I maintain session.
I tried Cookies and localStorage ,but could not get things working.Any help pls.
common.js :
var myApp = angular.module('MyApp', []);
myApp.controller('SearchController', function($scope,$http) {
$scope.clientVO = {};
$scope.getClientDetail = function(bcidNo) {
var response=$http.get('/testWeb/rest/clientData/'+ id);
response.success(function(data) {
console.log("getActor data: " + angular.toJson(data, false));
$scope.clientVO = data;
})
response.error(function(data, status, headers, config) {
alert("AJAX failed to get data, status=" + status);
})
}
});
home.html :
<!DOCTYPE html>
<html ng-app="MyApp">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>
<script src="../javascripts/common/common.js"></script>
</head>
<!--some code -->
<div ng-controller="SearchController">
<form class="content-left-body">
<div class="client-details">
<span class="content-right-header">Client Details</span>
<table>
<tr><td>
<label>Client ID:</label></td>
<td><input type="text" name="id" id="Search"
placeholder="Search" ng-model="id" class="search-box"/>
<img alt="Search" src="../images/search_img.png" ng-click= "getClientDetail(id);" style="margin-left:-15% ; margin-top:2.5%">
</td>
<td>
<div ng-show="clientVO.clientName==''"><label style="color:red">ID not found in database.</label></div>
</td>
</table>
<div>
<div>
<table style="width: 100%">
<tr >
<td><label>Client Name:</label></td>
<td><span ng-show="!clientVO.clientName">-</span><label ng-bind="clientVO.clientName"></label></td>
<td><label>AccNo:</label></td>
<td><input type="text" ng-disabled="!clientVO.clientName"></td>
</tr>
<tr >
<td><label>Contact Name:</label></td>
<td><span ng-show="!clientVO.contactName">-</span><label ng-bind="clientVO.contactName"></label></td>
<td><label>Validation Level:</label></td>
<td>
<select ng-disabled="!clientVO.clientName">
<option value="">-Please Select-</option>
<option value="">Level 1</option>
<option value="">Level 2</option>
<option value="">Level 3</option>
<option value="">Level 4</option>
</select>
</td>
</tr>
</table>
</div>
<div class="Data-details">
<div class="data">
<div class="content-left-body">
<span class="content-left-header">Data details</span>
<span class="content-left-header-small">Data classification</span>
<label id="clientClassification" ></label> <br><br>
<button id="btn-yellow" onClick=window.open("classification.html","fullscreen=yes");>Start</button>
</div>
</div>
</div>
</form>
<!---some code -->
</html>
I have this simple service to store data in localStorage (note that localStorage won't work here in SO)
angular.module('app', [])
.controller('AppCtrl', ['StorageSrv', function(StorageSrv){
StorageSrv.set('user', {first: 'John', last: 'Doe'})
console.log(StorageSrv.get('user'));
}]);
// This service can live in a separate file
angular.module('app')
.service('StorageSrv', ['$rootScope', function ($rootScope) {
var self = this,
prefix = 'your_prefix',
ls = window.localStorage;
self.set = function(key, val){
var obj = {};
_.set(obj, key, val);
ls.setItem(prefix, JSON.stringify(obj));
};
self.get = function(keyPath){
if (!keyPath || !_.size(keyPath))
return JSON.parse(ls.getItem(prefix));
else
return _.get(JSON.parse(ls.getItem(prefix)), keyPath, null);
};
self.delete = function(keyPath){
var key = prefix + '_'+_.trimStart(key, prefix);
var current = self.get(key);
_.unset(current, keyPath);
if (!_.size(current)){
self.update(key, {})
}
else {
self.update(key, current);
}
};
}])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="AppCtrl"></div>

Is this possible using only angular-formly?

So, I have this form, made using AngularJS here, which basically lets me create a purchase object to send to a server, i.e, it lets me select a store where I bought some items, set a "date of purchase" (just a text field for now), and add those items to the object I'm gonna send.
After the submit button it is shown how the model I'm going to send will look like, showing the id of the store, the "datetime", and an array of items.
My question is: Is there a way of doing this form using angular-formly only?
The question arises because I've been reading formly's docs and I haven't figured out how to make it create such a dynamic model as this form does, i.e., with a variable-length array of items of the purchase, or if it is at all possible.
Thanks in advance for any clue you can give me to answer this question :)
The code for the form is as follows:
(function(){
var app = angular.module('test', []);
})();
The html page:
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.5/angular.js"></script>
<script src="inab.js"></script>
<script src="PurchaseCtrl.js"></script>
</head>
<body ng-app="test">
<div ng-controller="PurchaseCtrl" class="col-md-4">
<h2>Purchase</h2>
<div class="panel panel-default">
<div class="panel-heading">Title</div>
<div class="panel-body">
<div class="form-group">
<label>Store</label>
<select class="form-control" ng-model="model.store">
<option ng-repeat="store in stores" value="{{store.id}}">{{store.name}}</option>
</select>
</div>
<div class="form-group">
<label>date-time</label>
<input class="form-control" type="text" ng-model="model.datetime"/>
</div>
<div ng-repeat="item in items">
<div class="form-group">
<div class="col-sm-2">
<label>{{item.label}}</label>
</div>
<div class="col-sm-8">
<input class="form-control" type="text" ng-model="item.nome" />
</div>
<div class="col-sm-2">
<button type="submit" class="btn btn-alert submit-button col-md-2" ng-click="removeItem()">remove item</button>
</div>
</div>
</div>
<button ng-click="addItem()">Add item</button>
</div>
</div>
<button type="submit" class="btn btn-primary submit-button" ng-click="onSubmit()">Submit</button>
<pre>{{model | json}}</pre>
</div>
</body>
</html>
The controller:
(function(){
angular.module('test').controller('PurchaseCtrl', ['$scope', function(scope){
scope.stores = [{id: 1, name:'Store 1'}, {id: 2, name: 'Store 2'}];
scope.items = [];
scope.datetime = '';
scope.store = '';
var i = 0;
scope.model = {
store: scope.store,
datetime: scope.datetime,
items: scope.items
};
scope.addItem = function(){
scope.items.push({label: 'algo' + (i++), nome:''});
}
scope.removeItem = function(){
scope.items.splice(scope.items.length - 1);
}
scope.onSubmit = function(){
console.log(scope.model);
}
}]);
})();
As #Satej commented, it was with repeated sections. Thanks :)

Default option in select is not working using AngularJS

I am following an AngularJS tutorial, and I wanted to validate my form. I decided to add a default option to the select element.
However, even after adding selected="", the browser won't show it as default.
I have tried this without AngularJS and it works fine, so I'm guessing the script is blocking something.
How can I define a default option for my select element?
PS: I'm using Google Chrome Version 44.0.2403.157 m
var controllers = angular.module('formsApp.Controllers', []);
controllers.controller('todoCtrl', function($scope) {
$scope.todoList = [{
action: 'Get groceries',
complete: false
}, {
action: 'Call plumber',
complete: false
}, {
action: 'Buy running shoes',
complete: true
}, {
action: 'Buy flowers',
complete: false
}, {
action: 'Call family',
complete: false
}];
$scope.addNewItem = function(newItem) {
$scope.todoList.push({
action: newItem.action + ' (' + newItem.location + ')',
complete: false
});
};
});
var app = angular.module('formsApp', ['formsApp.Controllers']);
form input.ng-invalid.ng-dirty {
background-color: lightpink;
}
<!DOCTYPE html>
<html data-ng-app="formsApp">
<head>
<title>Forms</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body>
<div id="todoPanel" class="panel" data-ng-controller="todoCtrl">
<h3 class="panel-header">
To Do List
<span class="label label-info">
{{(todoList | filter: {complete: false}).length }}
</span>
</h3>
<div class="row">
<div class="col-xs-4">
<div class="well">
<form name="todoForm" novalidate data-ng-submit="addNewItem(newTodo)">
<div class="form-group row">
<label for="actionText">Action:</label>
<input type="text" id="actionText" class="form-control" data-ng-model="newTodo.action" required="" />
</div>
<div class="form-group row">
<label for="actionLocation">Location:</label>
<select id="actionLocation" class="form-control" data-ng-model="newTodo.location" required="">
<option selected="">Home</option>
<option>Office</option>
<option>Mall</option>
</select>
</div>
<button type="submit" class="btn btn-primary btn-block" data-ng-disabled="todoForm.$invalid">
Add
</button>
</form>
</div>
</div>
<div class="col-xs-8">
<table class="table">
<thead>
<tr>
<th>#</th>
<th>Action</th>
<th>Done</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="item in todoList">
<td>
{{$index + 1}}
</td>
<td>
{{item.action}}
</td>
<td>
<input type="checkbox" data-ng-model="item.complete" />
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
From the dev guide for ngSelected;
The HTML specification does not require browsers to preserve the
values of boolean attributes such as selected. (Their presence means
true and their absence means false.) If we put an Angular
interpolation expression into such an attribute then the binding
information would be lost when the browser removes the attribute. The
ngSelected directive solves this problem for the selected attribute.
This complementary directive is not removed by the browser and so
provides a permanent reliable place to store the binding information.
In your controller add another property and reference it from there:
{
action: 'Call family',
complete: false,
selected: 'selected'
}];
{
action: 'Call family',
complete: false,
selected: ''
}];

How can I validate checkbox in angularjs?

Usually I use formName.inputName.$invalid to show error message input like this:
<input name="myInput" minlength="3" />
<span ng-show="myForm.myInput.$invalid">too short</span>
that won't be a problem.
But when I tried to validate checkbox,it seems difficult, there are the snippet at the end.
I want the effect that user should at least check one checkbox ,or you got the warning message.
How can I do that in a simple way at best?
// app.js
var formApp = angular.module('formApp', [])
.controller('formController', function($scope) {
// we will store our form data in this object
$scope.formData = {};
$scope.formData.favoriteColors = [{
'id':'1',
'name':'red'
},{
'id':'2',
'name':'green'
},{
'id':'3',
'name':'blue'
}];
$scope.cList = [];
$scope.checkList = function(index){
if($scope.myForm.favoriteColors.$pristine){
$scope.cList.push($scope.formData.favoriteColors[index]);
}
else{
angular.forEach($scope.formData.favoriteColors,function(value,key){
if(value.checked){
$scope.cList.push(value.id);
}
});
}
console.log('cList:%o',$scope.cList);
};
});
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<!-- CSS -->
<!-- load up bootstrap and add some spacing -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.20/angular.min.js"></script>
<link href="http://cdn.bootcss.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>
<style>
body { padding-top:50px; }
form { margin-bottom:50px; }
</style>
<!-- JS -->
<!-- load up angular and our custom script -->
<script src="lib/angular/angular.min.js"></script>
<script src="app.js"></script>
</head>
<!-- apply our angular app and controller -->
<body ng-app="formApp" ng-controller="formController">
<div class="col-xs-12 col-sm-10 col-sm-offset-1">
<h2>Angular Checkboxes and Radio Buttons</h2>
<form name="myForm">
<!-- NAME INPUT -->
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" name="name" ng-model="formData.name">
</div>
<!-- MULTIPLE CHECKBOXES -->
<label>Favorite Colors</label>
<div class="form-group">
<label class="checkbox-inline" ng-repeat="color in formData.favoriteColors">
<input type="checkbox" name="favoriteColors" ng-model="color.checked" ng-click="checkList($index)" required>{{color.name}}
</label>
<span class="danger" ng-show="myForm.favoriteColors.$invalid">Please check one color at least</span>
</div>
<!-- SUBMIT BUTTON (DOESNT DO ANYTHING) -->
<button type="submit" class="btn btn-danger btn-lg">Send Away!</button>
</form>
<!-- SHOW OFF OUR FORMDATA OBJECT -->
<h2>Sample Form Object</h2>
<pre>
dirty:{{ myForm.favoriteColors.$dirty }}
pristine:{{ myForm.favoriteColors.$pristine }}
valid:{{ myForm.favoriteColors.$valid }}
invalid:{{ myForm.favoriteColors.$invalid }}
error:{{ myForm.favoriteColors.$error }}
</pre>
</div>
</body>
</html>
Here is the live demo:http://jsbin.com/yigujoporu/1/
I use a count funtcion to update the number of checked checkbox.
Here is the live demo:http://jsbin.com/wowipi/4/edit?js,output
You can custom validation by another way
First, in your controller
$scope.cList = [];
$scope.checked = false;
$scope.checkList = function(index){
if($scope.myForm.favoriteColors.$pristine){
$scope.cList.push($scope.formData.favoriteColors[index]);
}
else{
if($scope.formData.favoriteColors[index].checked == true){
//checked
$scope.cList.push($scope.formData.favoriteColors[index]);
}else{
//uncheck
angular.forEach($scope.cList, function(value,key){
if($scope.formData.favoriteColors[index].id == value.id){
//remove it
$scope.cList.splice(key,1);
}
}
}
console.log('cList:%o',$scope.cList);
//new change
if($scope.cList.length >0) {
$scope.checked = true;
}else{
$scope.checked = false;
}
};
In your view
<div class="form-group">
<label class="checkbox-inline" ng-repeat="color in formData.favoriteColors">
<input type="checkbox" name="favoriteColors" ng-model="formData.favoriteColors[$index].checked" ng-click="checkList($index)" required>{{color.name}}
</label>
<span class="danger" ng-show="!checked">Please check one color at least</span>
</div>

Categories