I am new to Angularjs and practicing it by doing some tasks. Here I am creating an object in controller and the object values in my web page. But here the ng-show does not evaluate the below expression. But if I create a variable in controller as $scope.ngshow = false; it will work. Please help me why the below code did not worked.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<ul>
<li ng-show = "a.name"> Name {{a.name}} </li>
<li ng-show = "a.id"> Id {{a.id}}</li>
<li ng-show = "a.address"> Address {{a.address}}</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.a = {
'name' : 'false',
'id' : 'true',
'address' : 'false'
};
});
</script>
<p>ng-show didnt accept expressions.</p>
</body>
</html>
Thanks for your valuable time.
You should not use true or false as string
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.a = {
'name' : false,
'id' : true,
'address' : false
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<ul>
<li ng-show = "a.name"> Name {{a.name}} </li>
<li ng-show = "a.id"> Id {{a.id}}</li>
<li ng-show = "a.address"> Address {{a.address}}</li>
</ul>
</div>
<script>
</script>
<p>ng-show didnt accept expressions.</p>
well, apperenly it's a version conflict. This version 1.4.8 of angular ng show support value as boolean not string boolean. So you need to remove the quotes around the values
$scope.a = {
'name' : false,
'id' : true,
'address' : false
};
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.a = {
'name' : false,
'id' : true,
'address' : false
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<ul>
<li ng-show = "a.name"> Name {{a.name}} </li>
<li ng-show = "a.id"> Id {{a.id}}</li>
<li ng-show = "a.address"> Address {{a.address}}</li>
</ul>
</div>
But if you are using a lower version like 1.2.23 then angular identify string values as boolean if the values are true or false
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.a = {
'name' : 'false',
'id' : 'true',
'address' : 'false'
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<ul>
<li ng-show = "a.name"> Name {{a.name}} </li>
<li ng-show = "a.id"> Id {{a.id}}</li>
<li ng-show = "a.address"> Address {{a.address}}</li>
</ul>
</div>
Just remove the single quotes from true and false.If you put quotes on true and false , they are strings.In that case ng-show is checking whether variable is defined or not.In your case, since it have string true/false value, ng-show is considering expression as defined hence true.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<ul>
<li ng-show="a.name"> Name {{a.name}} </li>
<li ng-show="a.id"> Id {{a.id}}</li>
<li ng-show="a.address"> Address {{a.address}}</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.a = {
'name': false,
'id': true,
'address': false
};
});
</script>
<p>ng-show didnt accept expressions.</p>
</body>
</html>
Related
I have successfully received the JSON object from an API, which is evident from a console.log code. Now, I want to display the various elements in that JSON file. For example, the JSON contains elements like "name" and "url". How do I display these individually, in an h1 HTML element, after clicking the submit button and fetching the JSON file. I'm a newbie and sorry if this is an obvious question, I'm kinda stuck and need help. Thank you in advance!
My HTML Code is:
<body ng-app="myApp">
<div ng-controller="UserCtrl">
Search : <input type="text" placeholder="Search Employees"
ng-model="formData.searchText"/> <br/><br/>
<button ng-click="getByID()">Submit</button>
{{response.data.name}}
</body>
The JS is:
var myApp = angular.module('myApp', []);
myApp.controller('UserCtrl', function($scope, $http) {
var id = "my secret key comes here";
$scope.formData = {};
$scope.searchText;
$scope.getByID = function() {
$http.get("https://rest.bandsintown.com/artists/" + $scope.formData.searchText + "?app_id="+id)
.then(response => {
console.log(response.data.name)
})
}
});
Thank you so much in advance!
You need to use a variable to assign it with the response data and then use it in html. For example to display name from response.data.name:
<body ng-app="myApp">
<div ng-controller="UserCtrl as vm">
Search : <input type="text" placeholder="Search Employees"
ng-model="vm.searchText"/> <br/><br/>
<button ng-click="vm.getByID()">Submit</button>
<h1>{{ vm.name }}</h1>
</body>
In controller:
var myApp = angular.module('myApp', []);
myApp.controller('UserCtrl', function($http) {
let vm = this;
var id = "my secret key comes here";
vm.searchText;
vm.name;
vm.getByID = function() {
$http.get("https://rest.bandsintown.com/artists/" + vm.searchText + "?app_id="+id)
.then(response => {
console.log(response.data.name);
vm.name = response.data.name;
})
}
});
Put the data on $scope:
$scope.getByID = function() {
var url = "https://rest.bandsintown.com/artists/" + $scope.formData.searchText;
var params = { app_id: id };
var config = { params: params };
$http.get(url, config)
.then(response => {
console.log(response.data.name)
$scope.data = response.data;
})
}
Then use the ng-repeat directive:
<body ng-app="myApp">
<div ng-controller="UserCtrl">
Search : <input type="text" placeholder="Search Employees"
ng-model="formData.searchText"/> <br/><br/>
<button ng-click="getByID()">Submit</button>
{{data.name}}<br>
<div ng-repeat="(key, value) in data">
{{key}}: {{value}}
</div>
</div>
</body>
For more information, see
AngularJS ng-repeat Directive API Reference
https://plnkr.co/edit/oo05d6H6AxuJGXBAUQvr?p=preview
I have created an array of items and when I click on each item details page will be displayed ,for all the items in the array I have used same details page,can anyone look at my plunker and explain why the templateURL is not working when I click on an item?
var app = angular.module("myApp", ["ngRoute"]);
app.controller('mobileController', function($scope) {
$scope.items = [{
name: 'Iphone',
}, {
name: 'Oneplus'
}, {
name: 'Moto'
}];
});
app.config(function($routeProvider) {
$routeProvider
.when('/item/:itemName', {
templateUrl: 'details.html',
controller: 'ItemCtrl'
});
app.controller('ItemCtrl', ['$scope', '$routeParams',
function($scope, $routeParams) {
$scope.itemName = $routeParams.itemName;
}
]);
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></script>
<script src="script.js"></script>
<body ng-app="myApp" ng-controller="mobileController">
<h2> Welcome to Mobile Store</h2>
<p>Search:<input type="text" ng-model="test"></p>
<ul>
<li ng-repeat="item in items|filter:test">{{ item.name }}
</li>
</ul>
<div ng-view></div>
</body>
</html>
here is my details page
<!DOCTYPE html>
{{itemName}}
is it because of a mismatch?
.when('/item/:itemName', {
a href="/items/{{item}}"
there's an extra s there
Summary of problems:
Your ItemCtrl is currently defined inside your module's config function. Move it out of there
app.config(function($routeProvider) {
$routeProvider
.when('/item/:itemName', {
templateUrl: 'details.html',
controller: 'ItemCtrl'
});
}); // you were missing this
app.controller('ItemCtrl', ['$scope', '$routeParams',
Your route is /item/:itemName and since you're not using HTML5 mode, you need to create your href attributes with a # prefix. For example
ng-href="#/item/{{item.name}}"
Fixed demo here ~ https://plnkr.co/edit/rKHsBMFcXqJUGp8Blx7Q?p=preview
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>
i get this error when i start the app
this is the controller:
myApp
.controller('NavController',
['$scope', '$location', function ($scope, $location) {
$scope.navClass = function (page) {
var currentRoute = $location.path().substring(1) || 'main';
return page === currentRoute ? 'active' : '';
};
}]);
and this is the app.js:
angular.module('myApp',[
'ngRoute'])
.config(['$routeProvider',
function($routeProvider){
$routeProvider
.when('/',{
templateUrl:'views/main.html',
controller: 'mainCtrl'
})
.when('/team1',{
templateUrl:'views/team1.html',
controller: 'mainCtrl'
})
}]);
and the htmlIndex where i use the contoller:
<header>
<div class="container">
<div class="navbar">
<ul class="nav navbar-nav" ng-controller="NavController">
<li ng-class="navClass('home')"><a href='#/'>Home</a></li>
<li ng-class="navClass('home')"><a href='#/team1'>team1</a></li>
</ul>
</div>
</div>
</header>
i click the nav buttons nothing happens and in the console i get this error "Argument 'NavController' is not a function, got undefined"
Maybe you call controller in a wrong way. It should be called on a app like this:
angular.module('myApp')
.controller('NavController',
['$scope', '$location', function ($scope, $location) {
$scope.navClass = function (page) {
var currentRoute = $location.path().substring(1) || 'main';
return page === currentRoute ? 'active' : '';
};
}]);
Take a look at this fiddle for a complete code: https://jsfiddle.net/q91jozyr/
When you define the module with angular.module('myApp', ['ngRoute']) you need to save the reference in the variable myAppto reuse the module, when declaring the controller.
app.js:
var myApp = angular.module('myApp', ['ngRoute'])
Alternatively I suggest to call the controller by reusing the module like this:
controller:
angular.module('myApp').controller('NavController', [ /* etc... */ ]);
Note that the module is being reused, if you don't specifiy the dependencies again like angular.module('myApp') instead of angular.module('myApp', [ ]).
In both cases make sure the module myApp is bootstrapped by adding ng-app="myApp" to any of the parent elements, e.g. the <body>:
<body ng-app="myApp">
I am new to AngularJs and for stackoverflow too,hope will get a solution for my problem here. I`m trying to display the details of an experiment(in the same page)based on the name of the experiment which is coming from the URL when the name is clicked(index.html). Here the problem is,when I click an experiment name,it is coming in the URL but not able to fetch its details.Can anyone help me to solve.Here is my code.
//experiments.json
[
{
"sl_no" : "1",
"name" : "BCD adders",
"objective" : "It deals with the desinging of reversible BCD adders."
},
{"sl_no" : "2",
"name" : "Online Banking",
"objective" : "It deals with the online Transactions."}
]
//index.html
<!DOCTYPE html>
<html ng-app="experimentApp">
<head>
<script src="js/angular.min.js"></script>
<script src="js/angular-route.min.js"></script>
<script src="js/controller.js"></script>
</head>
<body>
<div id="main">
<nav class="navbar navbar-default">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="/">Angular Routing Example</a>
</div>
<br>
<ul class="nav navbar-nav navbar-left">
<div>
<ul ng-controller="ExperimentListCtrl">
<li ng-repeat="experiment in experiments">
<a href="#/{{experiment.name | encodeURI}}">
<strong>{{experiment.sl_no}}. {{experiment.name}}</strong><br>
</a>
</li>
</ul>
<div ng-include="experiment-detail.html"></div>
</div>
</ul>
</div>
</nav>
</div>
</body>
</html>
//controller.js
// create the module and name it experimentApp
var experimentApp = angular.module('experimentApp', ['ngRoute']);
// configure our routes
experimentApp.config(function($routeProvider) {
$routeProvider.
when('/:experimentName', {
templateUrl : 'experiment-detail.html',
controller : 'ExperimentDetailCtrl'
}).
otherwise({
redirectTo: '/'
});
});
experimentApp.factory('experiments', function($http){
function getData(callback){
$http({
method: 'GET',
url: 'experiments.json',
cache: true
}).success(callback);
}
return {
list: getData,
find: function(name, callback){
getData(function(data) {
var experiment= data.filter(function(entry){
return entry.name === name;
})[0];
callback(experiment);
});
}
};
});
experimentApp.controller('ExperimentListCtrl', function ($scope, experiments){
experiments.list(function(experiments) {
$scope.experiments = experiments;
});
});
experimentApp.controller('ExperimentDetailCtrl', function ($scope, $routeParams,
experiments){
experiments.find($routeParams.experimentName, function(experiment) {
$scope.experiment = experiment;
});
});
experimentApp.filter('encodeURI', function(){
return window.encodeURI;
});
//experiment-detail.html
<div>
<strong>{{experiment.sl_no}}. {{experiment.name}}</strong><br>
</br></br>
<strong>Aim :</strong>{{experiment.objective}}
</div>
You need to encode the experiment.name only, so change :
experimentApp.filter('encodeURI', function(){
return window.encodeURI;
});
to :
experimentApp.filter('encodeURI', function(stringToEncode){
return encodeUri(stringToEncode);
});