Getting ng-option text inside html - html

My Code:
HTML:
<select ng-model="selectedItem" ng-options="item.result as item.name for item in items"></select>
JS:
$scope.items = [{'name': 'Yes', 'result': true },{ 'name': 'No', 'result': false }];
I want to display Yes and No in the select box whereas I have to send true and false to the server when Yes or No is selected respectively.
I have another div where I have to display the option text (ie Yes or No (selected one) ). I used {{selectedItem.label}} but it is not working. Please help.

Used Sajeetharan's answer and updated it to meet your requirement.
Following is the code:
<!DOCTYPE html>
<html ng-app="todoApp">
<head>
<title>To Do List</title>
<link href="skeleton.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
<script src="MainViewController.js"></script>
</head>
<body ng-controller="dobController">
<select class="form-control" id="selection" ng-model="currentSelected" ng-options="selection.result as selection.name for selection in items"></select>
<div>
<h1> Selected one is : {{currentSelected? "Yes": (currentSelected == null)? "":"No"}} </h1>
</div>
<script>
var app = angular.module('todoApp', []);
app.controller("dobController", ["$scope",
function($scope) {
$scope.items = [{'name': 'Yes', 'result': true },{ 'name': 'No', 'result': false }];
}
]);
</script>
</body>
</html>

Demo
var app = angular.module('todoApp', []);
app.controller("dobController", ["$scope",
function($scope) {
$scope.items = [{'name': 'Yes', 'result': true },{ 'name': 'No', 'result': false }];
}
]);
<!DOCTYPE html>
<html ng-app="todoApp">
<head>
<title>To Do List</title>
<link href="skeleton.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
<script src="MainViewController.js"></script>
</head>
<body ng-controller="dobController">
<select class="form-control" id="selection" ng-model="currentSelected" ng-options="selection.result as selection.name for selection in items"></select>
<div>
<h1> Selected one is : {{currentSelected}} </h1>
</div>
</body>
</html>

Use directive to get the desired result of displaying the selected item name value but send the result value to backend.
var app = angular.module('app', []);
app.controller("myctrl", ["$scope",
function($scope) {
$scope.items = [{
'name': 'Yes',
'result': true
}, {
'name': 'No',
'result': false
}];
}
]);
app.filter('getvalue', function() {
return function(value, array) {
if (value !== undefined && value !== null) {
var selectedOption = array.filter(function(l) {
if (l.result == value) {
return l;
}
})[0];
return selectedOption["name"];
} else {
return "";
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="app" ng-controller="myctrl">
<select class="form-control" id="selection" ng-model="currentSelected" ng-options="selection.result as selection.name for selection in items"></select>
<div>
Displayed Text : {{currentSelected | getvalue:items}}
</div>
<div>
Value which will be send : {{currentSelected}}
</div>
</body>

Related

How to use ng if condition in a single div for multiple condition

I have a select dropdown,and divs coming from loop.Here when I change the drop down option to city,my div id should change to one,two three which comes from details column from json.Again when I change the drop down option to state,my div id should change to title1,title2 title3 which comes from title column from json.Here it is working fine but I am creating new divs for each condition,can it possible to make in a single div with multiple condition.Here is the code below.
HTML
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<select class="change" ng-model="x" ng-change="update()">
<option value="city">Cities</option>
<option value="state">States</option>
<option value="country">Countries</option>
</select>
<div ng-if="id=='city'">
<div ng-repeat="emp in groups" ng-attr-id="{{emp.details}}" >hello</div>
</div>
<div ng-if="id=='state'">
<div ng-repeat="emp in groups" ng-attr-id="{{emp.title}}" >hello</div>
</div>
<div ng-if="id=='country'">
<div ng-repeat="emp in groups" ng-attr-id="{{emp.name}}" >hello</div>
</div>
script
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.groups = [
{
title: 'title1',
name:'name1',
details:'one'
},
{
title: 'title2',
name:'name2',
details:'two'
},
{
title: 'title3',
name:'name2',
details:'three'
}
]
$scope.update = function() {
if($scope.x == 'city'){
$scope.id='city';
}
if($scope.x == 'state'){
$scope.id='state';
}
if($scope.x == 'country'){
$scope.id='country';
}
}
});
To achieve the desired result, try to:
create an attr for each value - city, state and country, like so:
if($scope.x == 'city'){
$scope.id='city';
$scope.attr = 'details';
}
Use {{emp[attr]}} to display values based on the dropdown selection:
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.groups = [{
title: 'title1',
name: 'name1',
details: 'one'
},
{
title: 'title2',
name: 'name2',
details: 'two'
},
{
title: 'title3',
name: 'name2',
details: 'three'
}
]
$scope.update = function() {
if ($scope.x == 'city') {
$scope.id = 'city';
$scope.attr = 'details';
}
if ($scope.x == 'state') {
$scope.id = 'state';
$scope.attr = 'title';
}
if ($scope.x == 'country') {
$scope.id = 'country';
$scope.attr = 'name';
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<select class="change" ng-model="x" ng-change="update()">
<option value="city">Cities</option>
<option value="state">States</option>
<option value="country">Countries</option>
</select>
<div ng-repeat="emp in groups" ng-attr-id="{{emp[attr]}}">{{emp[attr]}}</div>
</div>
</div>
codepen - https://codepen.io/nagasai/pen/wRQWRM
To this in a singal element you can use a nested ternary operator. For your case it will look like that:
<div ng-repeat="emp in groups" ng-attr-id="{{id=='city' ? emp.details : id=='state' ? emp.title : emp.name}}" >hello</div>
I didn't implement this on angular 1 but it works on angular 2. Angular built in directive (ngif, ngfor ngclass etc) works almost same for both versions.

Custom Directives and Template doesn't work

I'm trying to make a custom directive that will show some elements that i previously declared in the MainController
HTML body:
<body ng-app="myApp" ng-controller="MainController">
<h1> Choose your Car </h1>
<div ng-repeat="car in cars">
<my-pattern info="car"></my-pattern>
</div>
<script src="js/MainController.js"></script>
<script src="js/myPattern.js"></script>
</body>
MainController:
angular.module('myApp').controller('MainController',function($scope) {
$scope.cars=[
{
icon: 'imgs/lamborghini.jpg',
name: 'Lamborghini',
price: 100000
},
{
icon: 'imgs/audi.png',
name: 'Audi',
price: 80000
}
];
});
Custom Directive
angular.module('myApp').directive('myPattern', function() {
return{
restrict: 'E',
scope: {
info: '='
},
templateUrl: 'js/directives/myPattern.html'
};
});
Template:
<img ng-src="{{info.icon}}">
<h2>{{info.name}}</h2>
<p>{{info.price}}</p>
If i don't use the directive but i just make the output whit the expressions <h2>{{car.name}}</h2> like this it work but with the custom directive it doesn't show me nothing.
I have all in different files.
This is working for me. There must be a issue with the location of your template with respect to your current HTML:
var app = angular.module("myApp", []);
angular.module('myApp').controller('MainController', function($scope) {
$scope.cars = [{
icon: 'imgs/lamborghini.jpg',
name: 'Lamborghini',
price: 100000
}, {
icon: 'imgs/audi.png',
name: 'Audi',
price: 80000
}];
});
angular.module('myApp').directive('myPattern', function() {
return {
restrict: 'E',
scope: {
info: '='
},
templateUrl: 'js/directives/myPattern.html'
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MainController">
<h1> Choose your Car </h1>
<div ng-repeat="car in cars">
<my-pattern info="car"></my-pattern>
</div>
<script type="text/ng-template" id="js/directives/myPattern.html">
<img ng-src="{{info.icon}}">
<h2>{{info.name}}</h2>
<p>{{info.price}}</p>
</script>
</div>
I solved, i didn't synchronize the directives in the Custom Directive and in the body HTML. The code was right but i make a mistake with the calling script of the directive:
<script src="js/directives/myPattern.js"></script>

ion-nav-view not working when trying to transition to new template

I am trying to figure out how to transition from one url to another using ion-nav-view. Visual Studio compiles the code and doesnt throw any errors when trying to load the templates/events.html in the tab. Any suggestions are welcome
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
<link rel="stylesheet" type="text/css" href="css/index.css">
<title>SlidingTransitionwithAPI</title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<script src="lib/ionic/js/ionic.bundle.js"> </script>
<script src="cordova.js"></script>
<script src="lib/angular-ui-router/release/angular-ui-router.js"></script>
<script src="lib/angular-ui-router/release/angular-ui-router.min.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<script src="lib/ionic-ion-swipe-cards/ionic.swipecards.js"></script>
<script src="lib/collide/collide.js"></script>
<script src="lib/ionic-ion-tinder-cards/ionic.tdcards.js"></script>
</head>
<body ng-app="starter" no-scroll>
<ion-nav-view>
</ion-nav-view>
</body>
app.js:
angular.module('starter', ['ionic', 'starter.controllers', 'ionic.contrib.ui.tinderCards', 'ui.router'])
.run(function ($ionicPlatform) {
$ionicPlatform.ready(function () {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleLightContent();
}
});
})
.config(function ($stateProvider, $urlRouterProvider) {
// Ionic uses AngularUI Router which uses the concept of states
// Learn more here: https://github.com/angular-ui/ui-router
// Set up the various states which the app can be in.
// Each state's controller can be found in controllers.js
$stateProvider
.state('FindEvents', {
url: '/findEvents',
templateUrl: 'templates/events.html',
controller: 'EventsCtrl'
})
.state('favorites', {
url: '/favorites',
templateUrl: 'templates/favorites.html',
controller: 'FavoritesCtrl'
})
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/findEvents');
});
controllers.js:
angular.module('starter.controllers', [])
.directive('noScroll', function () {
return {
restrict: 'A',
link: function ($scope, $element, $attr) {
$element.on('touchmove', function (e) {
e.preventDefault();
});
}
}
})
.controller('EventsCtrl', function ($scope, $state) {
var cardTypes = [
{ image: './images/event1.jpeg', title: 'New Apple Release' },
{ image: './images/event2.jpeg', title: 'Digital Conference' },
{ image: './images/event3.jpg', title: 'Skyline Sessions' },
{ image: './images/event4.jpg', title: 'Secret Rooftop Party' },
{ image: './images/event5.jpeg', title: 'Smoking Lights' },
{ image: './images/event6.jpg', title: 'Antibes Color Run' },
{ image: './images/event7.jpg', title: 'Tomorrowland' },
{ image: './images/event8.jpeg', title: 'Steve Aoki Lighting Up Town' },
{ image: './images/event9.jpeg', title: 'Nice Yacht Party' },
{ image: './images/event10.jpg', title: 'Night Pool Party' },
];
$scope.cards = [];
$scope.addCard = function () {
for (var p = 0; p < 10; p++) {
var newCard = cardTypes[p];
newCard.id = Math.random();
$scope.cards.push(angular.extend({}, newCard));
}
}
$scope.addCard();
$scope.cardDestroyed = function (index) {
$scope.cards.splice(index, 1);
};
$scope.cardSwipedLeft = function (index) {
console.log('Left swipe');
}
$scope.cardSwipedRight = function (index) {
console.log('Right swipe');
}
$scope.cardDestroyed = function (index) {
$scope.cards.splice(index, 1);
console.log('Card removed');
}
//Transitioning between states
$scope.Favorites = function () {
$state.go('favorites');
}
});
events.html:
<ion-view view-title="Time 'N Joy '" ng-controller="EventsCtrl">
<ion-content ng-app="starter" >
<ion-pane>
<div class="bar bar-header bar-dark">
<button class="button button-clear button-icon icon ion-navicon"></button>
<div class="h1 title" font="6" color="white">Event Finder</div>
<button class="button button-clear" ng-click="Favorites()">
<i class="icon ion-heart"></i>
</button>
</div>
<td-cards>
<td-card id="td-card" ng-repeat="card in cards" on-destroy="cardDestroyed($index)"
on-swipe-left="cardSwipedLeft($index)" on-swipe- right="cardSwipedRight($index)"
on-partial-swipe="cardPartialSwipe(amt)">
<div class="title">
{{card.title}}
</div>
<div class="image">
<div class="no-text overlayBox"><div class="noBox boxed">Trash</div></div>
<img ng-src="{{card.image}}">
<div class="yes-text overlayBox"><div class="yesBox boxed" id="centerMe">Save</div></div>
</div>
</td-card>
</td-cards>
</ion-pane>
</ion-content>
</ion-view>
It is probably something very straigh forward but I have gone through countless examples and documents but cant find the error.

Cannot get separate views to appear in index.html, and controller is also not working

I'm just starting out with Angular and most of programming in general. I'm trying to make a separate view1.html file appear on my index.html page but it won't, so I'm assuming it's a routing problem. I tried pasting the view1.html content in the body of my index.html to test it and it wasn't showing the controller content either. I'm sure they're simple mistakes but I can't find them. view.html is in a separate folder called views. I only have the javascript in the index.html page for convenience.
index.html
<!DOCTYPE html>
<html lang="en" ng-app='demoApp'>
<head>
<meta charset="UTF-8">
<title>First Angular App</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular.min.js"></script>
<body>
<div>
<div ng-view></div>
</div>
<script>
// create module called "demoApp" under the variable name "demoApp"
var demoApp = angular.module('demoApp', []);
// ROUTING
demoApp.config(function ($routeProvider) {
$routeProvider
.when ('/',
{
controller: 'SimpleController',
templateUrl: 'views/view1.html'
})
.when('/view2',
{
controller: 'SimpleController',
templateUrl: 'views/view2.html'
})
.otherwise({ redirectTo: '/' });
});
// CONTROLLERS
demoApp.controller('SimpleController', function ($scope) {
$scope.customers = [
{ name: 'Caleb', city: 'Indianapolis' },
{ name: 'Samantha', city: 'Zionsville' },
{ name: 'Tim', city: 'Palo Alto' }
];
$scope.addCustomer = function () {
$scope.customers.push(
{
name: $scope.newCustomer.name,
city: $scope.newCustomer.city
});
};
}
</script>
</body>
</html>
view1.html
<h2>View 1</h2>
Name:
<input type="text" ng-model="name" />
<ul>
<li ng-repeat="cust in customers"></li>
</ul>
Customer Name:
<input type="text" ng-model="newCustomer.name" />
<br>Customer City:
<input type="text" ng-model="newCustomer.city" />
<br>
<button ng-click="addCustomer()">Add Customer</button>
View 2
</div>
You need to include the script for angular's router.
<head>
<meta charset="UTF-8">
<title>First Angular App</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular-route.min.js"></script>
Also, looks like you're missing a closing </head> tag.
Here's a working version of your HTML file:
<!DOCTYPE html>
<html lang="en" ng-app='demoApp'>
<head>
<meta charset="UTF-8">
<title>First Angular App</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular-route.js"></script>
</head>
<body>
<div>
<div ng-view></div>
</div>
<script>
// create module called "demoApp" under the variable name "demoApp"
var demoApp = angular.module('demoApp', ['ngRoute']);
// ROUTING
demoApp.config(function ($routeProvider) {
$routeProvider
.when ('/',
{
controller: 'SimpleController',
templateUrl: 'view1.html'
})
.when('/view2',
{
controller: 'SimpleController',
templateUrl: 'view2.html'
})
.otherwise({ redirectTo: '/' });
});
// CONTROLLERS
demoApp.controller('SimpleController', function ($scope) {
$scope.customers = [
{ name: 'Caleb', city: 'Indianapolis' },
{ name: 'Samantha', city: 'Zionsville' },
{ name: 'Tim', city: 'Palo Alto' }
];
$scope.newCustomer = { name: "", city: ""};
$scope.addCustomer = function () {
$scope.customers.push(
{
name: $scope.newCustomer.name,
city: $scope.newCustomer.city
});
};
});
</script>
</body>
</html>

Using ng-grid in partial page

Is there any example of using ng-grid in partial pages. Whenever I try to use, an error pops up as TypeError: Cannot set property 'myData' of undefined.
My App.js
'use strict';
// Declare app level module which depends on filters, and services
angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives', 'myApp.controllers', 'ngGrid']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view1', {templateUrl: 'partials/partial1.html', controller: 'MyCtrl1'});
$routeProvider.when('/view2', {templateUrl: 'partials/partial2.html', controller: 'MyCtrl2'});
$routeProvider.otherwise({redirectTo: '/view1'});
}]);
Controller.js
'use strict';
/* Controllers */
angular.module('myApp.controllers', ['ngGrid']).
controller('MyCtrl1', [function ($scope) {
$scope.myData = [{name: "Moroni", age: 50},
{name: "Tiancum", age: 43},
{name: "Jacob", age: 27},
{name: "Nephi", age: 29},
{ name: "Enos", age: 34 },];
$scope.gridOptions = {
data: 'myData',
columnDefs: [{ field: 'name', displayName: 'Name' },
{ field: 'age', displayName: 'Age', cellTemplate: '<div ng-class="{green: row.getProperty(col.field) > 30}"><div class="ngCellText">{{row.getProperty(col.field)}}</div></div>' }],
showGroupPanel: true
};
}])
.controller('MyCtrl2', [function() {
}]);
//MyCtrl1.$inject = ['$scope'];
Partial1.html
<p>This is the partial for view 1.</p>
<div class="gridStyle" ng-grid="gridOptions"></div>
<div style="clear:both"/>
<p>{{ myData | json }}</p>
Partial2.html
<p>This is the partial for view 2.</p>
<p>
Showing of 'interpolate' filter:
{{ 'Current version is v%VERSION%.' | interpolate }}
</p>
And index.html
<!doctype html>
<html xmlns:ng="http://angularjs.org" id="ng-app" lang="en" ng-app="myApp">
<head>
<meta charset="utf-8">
<title>My AngularJS App</title>
<link rel="stylesheet" href="css/app.css"/>
<link rel="stylesheet" href="css/bootstrap.css">
<link rel="stylesheet" href="css/ng-grid.css">
<link rel="stylesheet" href="css/Style.css">
<!-- In production use:
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
-->
<script src="js/jquery-1.9.1.min.js"></script>
<script src="lib/angular/angular.js"></script>
<script src="js/ng-grid-2.0.5.min.js"></script>
<script src="js/app.js"></script>
<script src="js/services.js"></script>
<script src="js/filters.js"></script>
<script src="js/directives.js"></script>
<script src="js/controllers.js"></script>
</head>
<body>
<ul class="menu">
<li>view1</li>
<li>view2</li>
</ul>
<div ng-view></div>
<div>Angular seed app: v<span app-version></span></div>
</body>
</html>
Can you please say, why 'myData' is unavailable in Partial1.html?
Thanks in advance.
It is probably too late, but for the code right here
{name: "Enos", age: 34 },];
you don't need the coma. It should read:
{name: "Enos", age: 34 }];