MVC Dropdownlist with Angular Selecting default - angularjs

I am new to both MVC and AngularJS.
I am having a layout page and in layout page partial view which is having dropdown and render body.
On selection change of any value content will change of view in render body.
I am using MVC #Html.DropDownList Since my data List is in session.
Now I want to change view data on change of dropdown values I am doing it with Angular.
Below is my code of partial view.
#Html.DropDownList("LoanAccountTypeModels", new SelectList(((MyModel.UserDetailsModel)Session["UD"]).LoanAccountTypeModels), new { style = "height: 30px; width:250px;", ng_change = "UpdateChildViews()", ng_init="LoanAccountTypeModel = options[0]" , ng_model = "LoanAccountTypeModel" })
my _Layout page is
<!DOCTYPE html>
<html lang="en">
<head>
<script src="~/Scripts/angular.js"></script>
#Styles.Render("~/Content/css")
#Styles.Render("~/css/_Layout")
#Scripts.Render("~/js/jquery.js")
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#Scripts.Render("~/js/_Layout.js")
</head>
<body ng-app="ClientPortalGlobalNGApp">
<div id="wrapper" ng-controller="ClientPortalGlobalNGController">
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<div> <a class="navbar-brand" href="index.html"><img src="../assets/img/axis_bank_logo.png" style="width:65%;"> </a></div>
</div>
#Html.Partial("_HeaderPartial")
</nav>
<h3>{{HomePageModel.TotalSanctionedAmt}}</h3>
#RenderBody();
</div>
</body>
and my _layout.js page is
function ClientPortalGlobalNGController($scope, $http) {
$scope.UpdateChildViews = function (ddlAccountType) {
if ($scope.CurrentSelected == "Home") {
$scope.HomePageModel = { TotalSanctionedAmt: "10", CustomerDetail: { PrimaryHolderName: "X" } };
}
}
}
var app = angular.module("ClientPortalGlobalNGApp", []);
app.controller("ClientPortalGlobalNGController", ClientPortalGlobalNGController);
I have tried $scope.form = { type: $scope.typeOptions[0].value }; in controller then it is selecting default but it is giving TypeError: Cannot read property '0' of undefined and then angular code is not working and rendering as {{HomePageModel.TotalSanctionedAmt}} in final HTML instead of blank value.
Please suggest. I have been wandering on Stack overflow for 2 days. but no help.
Also please suggest me the best way to do it.

Related

How to set default value of custom radio button in a modal

Background:
So I am working with a modal box for searching through a list of task entries within a database using a form to narrow results. In this modal box, there is a custom radio button that's used for selecting whether or not the task is in progress (simple "Yes" or "No" option). The goal is to set the "No" option as the default value whenever the modal is called. Currently, I am using data-ng-init; however, this only works the first time the modal is opened. If the user closes the modal and reopens it, the default value is no longer set. Below is a sample of what this custom button looks like:
<div class="col-sm-6">
<div style="margin-bottom:10px">
<button type="button" data-ng-init="tr.taskInProgress('No')"
title="Task In Progress: No" data-ng-click="tr.taskInProgress('No')"
style="border:0;background:transparent">
<img src="../images/selected.png" data-ng-switch-when="No" />
<img src="../images/Deselect.png" data-ng-switch-when="Yes" />
<img data-ng-switch-when="" src="/nc/images/Deselect.png" /></button>
<text>No
</div>
(another similar button, but for 'yes')
</div>
In the accompanying .js file, the following is used to help populate this modal:
/*--------- Get Tasks ---------*/
tr.closeGetTaskModal = closeGetTasModal;
tr.displayGetTaskMessage = true;
tr.selectedStatusType = getStatusType;
tr.trackingId = '';
tr.performGetTask = performGetTask;
tr.isTaskInProgess = isTaskInProgress;
And, in the same .js file, the following function is used to modify the radio:
function isTaskInProgress(newValue) {
tr.isTaskInProgress = newValue;
}
I have been looking through others iterations on how they handle such cases, but I have been unlucky and have not found anything similar enough to what I am working with that works. I have tried setting the default in the Get Tasks section by modifying isTaskInProgress('No'), but this only locked the modal and I couldn't modify the option. I have tried setting the default inside the isTaskInProgress function; however, this only worked when the button was clicked, it failed to set a default. I tried seeing if data-ng-default would work; however, this didn't seem to be a recognized parameter. Does anyone have suggestions on how to modify this to get the desired results? Thank you all in advance for your help
Small Disclaimer
I am taking the liberty of assuming you are using UI Bootstrap (since I see bootstrap classes in your sample HTML), so will be using Uib Modal in my example.
Bootstrap Modal docs: https://angular-ui.github.io/bootstrap/#!#modal
Resolver / Callback Solution
You will most likely want to use the controller to set your tr.isTaskInProgress flag rather than using the ng-init directive (a bit more flexibility / readability).
Set tr.isTaskInProgress to false at the top of your target controller function, then pass its value to your modal as a property in a "Modal Resolve Object".
Bootstrap's explanation of the Resolve Object: https://angular-ui.github.io/bootstrap/#!#ui-router-resolves
Code
function MainController($scope, $uibModal) {
let vm = this;
vm.isTaskInProgress = false;
// When you open the modal, pass in the isTaskProgress value
let modalInstance = $uibModal.open({
templateUrl: 'myModalContent.html', // Points to the script template
controller: 'ModalController', // Points to the controller
controllerAs: 'mc',
windowClass: 'app-modal-window',
backdrop: 'static',
resolve: {
isTaskInProgress: function() {
// pass the task state to the Modal
return vm.isTaskInProgress;
}
}
});
// handle the value(s) passed back from the modal
modalInstance.result.then(returnedTaskState => {
// reassign the returned value of the modal
if (returnedTaskState !== null) {
vm.isTaskInProgress = returnedTaskState;
}
});
}
Working Example
https://plnkr.co/ryK7rG
In the interest of time, I've changed some of the variable / method names from what you have in your snippets. In the example, you can...
Set the In Progress value before you open the modal and the modal reflects the In Progress value.
Change the In Progress value inside the modal. On closing the modal, the value will be updated in the main page.
SO Snippet
I realize the SO Snippet window is not exactly the best place for this example, but just tossing my example code in here in case Plunker is inconvenient for some reason.
(function() {
"use strict";
let app = angular
.module("myApp", ["ui.bootstrap"])
.controller("MainController", MainController);
MainController.$inject = ["$scope", "$timeout", "$uibModal"];
function MainController($scope, $timeout, $uibModal) {
/**
* John Papa Style Guide
* https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md
* */
let vm = this;
// ==== scoped variables ====
vm.title = "AngularJS - Passing Toggled Values to a Modal"
vm.taskInProgress = false;
vm.taskButtonLocked = false;
// ==== functions hoist ====
vm.beginTask = _beginTask;
function _beginTask() {
vm.modalIsOpen = true;
// do work
openModal();
}
// ==== local functions ====
function openModal() {
// open the modal with configurations
let modalInstance = $uibModal.open({
templateUrl: 'myModalContent.html', // Points to my script template
controller: 'ModalController', // Points to my controller
controllerAs: 'mc',
windowClass: 'app-modal-window',
backdrop: 'static',
resolve: {
taskInProgress: function() {
// pass the task state to the Modal
return vm.taskInProgress;
}
}
});
// handle the value(s) passed back from the modal
modalInstance.result.then(returnedTaskState => {
// reset control values after modal is closed
vm.taskButtonLocked = false;
vm.modalIsOpen = false;
// reassign the returned value of the modal
console.log("returnedTaskState: ", returnedTaskState);
if (returnedTaskState !== null) {
vm.taskInProgress = returnedTaskState;
}
});
}
}
})();
(function() {
'use strict';
angular
.module('myApp')
.controller('ModalController', ModalController);
ModalController.$inject = ['$scope', '$timeout', '$uibModalInstance', 'taskInProgress'];
function ModalController($scope, $timeout, $uibModalInstance, taskInProgress) {
// Assign Cats to a Modal Controller variable
let vm = this;
vm.inProgress = taskInProgress;
console.log("taskInProgress", taskInProgress)
$scope.submit = function() {
$uibModalInstance.close(vm.inProgress);
}
$scope.close = function() {
$uibModalInstance.close(null);
}
}
})();
input[type="radio"]:hover {
cursor: pointer;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>AngularJS Plunk</title>
<link rel="stylesheet" href="style.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<!-- JQuery and Bootstrap -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!-- Angular Stuff -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.8/angular.js"></script>
<!-- UI Bootstrap Stuff -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/2.5.0/ui-bootstrap-tpls.min.js"></script>
<!-- Our Angularjs App -->
<script type="text/javascript" src="app.js"></script>
</head>
<body ng-app="myApp" ng-controller="MainController as tr">
<!-- ==== MAIN APP HTML ==== -->
<div class="container" style="padding:1em;">
<div class="row">
<div class="col-xs-12">
<div class="jumbotron text-center">
<h2>{{ tr.title }}</h2>
<h4><em>SO Question #55362380</em></h4>
<h4><em>AngularJS - v1.7.8</em></h4>
</div>
</div>
<div class="col-xs-12">
<form>
<div class="form-group">
<h3>Task In Progress</h3>
<div>
<label>Yes:</label>
<input type="radio"
ng-checked="tr.taskInProgress"
ng-click="tr.taskInProgress = true"
ng-disabled="tr.modalIsOpen">
</div>
<label>No:</label>
<input type="radio"
ng-checked="!tr.taskInProgress"
ng-click="tr.taskInProgress = false"
ng-disabled="tr.modalIsOpen">
</div>
<div class="form-group">
<label>Open the modal:</label>
<button type="button"
class="btn btn-success"
ng-click="tr.beginTask();"
ng-disabled="tr.taskButtonLocked">
<span>Begin Task</span>
</button>
</div>
</form>
</div>
</div>
</div>
<!-- ==== MODAL HTML TEMPLATE ==== -->
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-header">
<h3 class="modal-title" id="modal-title">I'm a modal!</h3>
</div>
<div class="modal-body" id="modal-body">
<form>
<div class="form-group">
<label>Task State:</label>
<div style="padding:1em;background:rgba(200, 214, 229,0.3);">
<p>
<span ng-show="!mc.inProgress">
<span>Task is not in progress... </span>
<i class="fa fa-check-square" aria-hidden="true"></i>
</span>
<span ng-show="mc.inProgress">
<span>Task is in progress... </span>
<i class="fa fa-spinner fa-spin" aria-hidden="true"></i>
</span>
</p>
</div>
</div>
<div class="form-group" style="padding-top:1em;">
<h3>Task In Progress</h3>
<div>
<label>Yes:</label>
<input type="radio"
ng-checked="mc.inProgress"
ng-click="mc.inProgress = true">
</div>
<label>No:</label>
<input type="radio"
ng-checked="!mc.inProgress"
ng-click="mc.inProgress = false">
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-primary" type="button" ng-click="submit()">OK</button>
<button class="btn btn-warning" type="button" ng-click="close()">Cancel</button>
</div>
</script>
</body>
</html>

how to create buttons in angularjs

I am making a game that has 50 buttons and everybutton has an identity as a color and an id. On clicking every button there color changes to what it has been defined. If the user clicks on the 25th button , he wins. Only three tries for clicking. I am however unable to do the first step of creating buttons. Please help. I use angularjs1.
<html ng-app="Bluebox">
<head>
<title>BlueBox</title>
<script src="angular.js"></script>
</head>
<body>
<div ng-controller="BoxController">
<button type="button" value = "bluebox" >
<li ng-repeat="x in boxlength">
{{index+1}}
</li>
</button>
</div>
<script>
angular.module("Bluebox",[])
.controller("BoxController",["$scope",function($scope){
$scope.boxlength=50;
$scope.index=0;
}])
</script>
</body>
</html>
Your ng-repeat is not at the right place. You want to repeat buttons.
<button ng-repeat="..." type="button" value="bluebox"></button>
Then the format of ng-repeat is not correct. This directive doesn't repeat a number of times, it repeats in an array.
What we usually do is create a method that create an array based on a number:
<button ng-repeat="i in times(number)" type="button" value="bluebox"></button>
Get number could look like:
$scope.number = 5;
$scope.times= function(x) {
return new Array(num);
}
Since the array created has indentical "values" you need to track by $index
function Main($scope) {
$scope.number = 50;
$scope.times= function(x) {
return new Array(x);
}
}
angular.module('test', []);
angular.module('test')
.controller('Main', Main);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.js"></script>
<div ng-app="test">
<div ng-controller="Main">
<button ng-repeat="i in times(number) track by $index" type="button">{{$index}}</button>
</div>
</div>

hide image comes from ng-repeat in angular

Question is quite simple but i am not able to hide image. Here is the code.
I am fetching the image details from database and showing them in grid format. Here is the code.
<span class="close" id="close">×</span>
<div class="my-gallery" itemscope id="grid" >
<figure itemprop="associatedMedia" >
<a href="{{imageUrl}}" id="thumb" name="{{pid[$index]}}" class="thumbnail " itemprop="contentUrl" data-id="{{pid[$index]}}" data-size="800x600">
<img src="" class="img-responsive " data-id="{{pid[$index]}}" id="{{pid[$index]}}" ng-src="{{thumb[$index]}}" style="min-height:50px;height:50px;">
</a>
</figure>
</div>
</div>
and here are more code.
$scope.myFunc = function(btnId) {
alert(btnId);
document.getElementById(btnId).style.visibility = "visible";
};
I want to hide the respective image. there could be multiple image but image id is different. So, what i want is when user click on any image it will hide.
Please advise how can i do that.
First of all Don't use getElementById.In angular you can simple bind the $scope variable.
Have a variable with the image object to show/hide. Make it true or false when you need to show/not.
On ng-click you can set the variable to be false. bind the variable to the element, so that you can hide whenever necessary.
<div ng-if="img.show">
<img src="" class="img-responsive " data-id="{{pid[$index]}}" id="{{pid[$index]}}" ng-src="{{thumb[$index]}}" style="min-height:50px;height:50px;">
</a>
</div>
DEMO
angular.module('webapp', [])
.controller('AppCtrl', function($scope) {
$scope.data = [
{
"id": 5454554,
"Url": "https://farm4.staticflickr.com/3261/2801924702_ffbdeda927_d.jpg",
"show":true
},
{
"id": 5454554,
"Url": "https://farm4.staticflickr.com/3261/2801924702_ffbdeda927_d.jpg",
"show":true
}
];
$scope.hide = function(img){
img.show = false;
}
});
<!DOCTYPE html>
<html ng-app="webapp">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>
</head>
<body ng-controller="AppCtrl">
<div class="add-pic-box1 col-md-3">
<div ng-repeat="img in data" >
<div ng-if="img.show">
<img class="thumb" ng-model="add_new_ads_mdl.img_add" imgid = "{{img._id}}" src="{{img.Url}}" />
<button ng-click="hide(img)"> HIDE ME </button>
</div >
</div>
</div>
</body>
</html>
You can use ng-click with $event
<div ng-app="app" ng-controller="Ctrl">
Click me
</div>
app.controller("Ctrl", function($scope) {
$scope.removeMe = function(event) {
event.toElement.remove()
};
});
Example

I can't get the response from BreweryDB API to show in my simple app

I am working with the BreweryDB API and I can't even get the response to show in my simple app.
Here is the app.js file that houses the controller. I am simply using a HTTP GET to load the API data.
angular.module('BreweryGuideApp', [])
.controller('BreweryGuideController', function($scope, $http){
var pendingTask;
if($scope.search === undefined){
$scope.search = "300 Suns Brewing"; // init search bar data
fetch(); // call fetch function
}
$scope.change = function(){
if(pendingTask){
clearTimeout(pendingTask);
}
pendingTask = setTimeout(fetch, 800);
};
function fetch(){
$http.get("https://api.brewerydb.com/v2/brewery/x4vqAl?key=cc12540abedfa669021307d4ba111d87&format=json")
.success(function(response){ $scope.details = response.data; }); //get API response on success
} //end fetch
}); // end controller
Here is the HTML file:
<!DOCTYPE html>
<html>
<head>
<title ng-bind="'Brewery.Guide - ' + data.name"></title>
<link rel="stylesheet" href="css/animate.min.css">
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/bootstrap.min.css">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="utf-8">
</head>
<body ng-app="BreweryGuideApp" ng-controller="BreweryGuideController">
<div class="container-fluid outerdiv">
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#"><b>Brewery.Guide</b> <span class="span-style">Get Yer Drink On</span></a>
</div>
</div>
</nav>
<noscript>
<div class="nojs">Javascript is either disabled or not supported in your browser. Please enable it or use a Javascript enabled browser.</div>
</noscript>
<div class="animated zoomInRight">
<div class="input-group search-bar">
<input type="text" ng-model="search" ng-change="change()" onclick="select()" class="form-control" placeholder="Enter brewery name" autofocus />
<span class="input-group-addon bar-style"><i class="glyphicon glyphicon-search"></i></span>
</div>
<div id="main-info" ng-include="'partials/main-info.html'" class="col-md-8"></div>
<div id="related-results" ng-include="'partials/related-results.html'" class="col-md-4 animated bounce related-results"></div>
</div>
</div>
<script src="js/angular.min.js"></script>
<script src="js/app.js"></script>
</body>
</html>
And this is the main-info.html to be inserted using the ng-include directive:
<div ng-if="details.status!=verified">
Loading results...
</div>
<div ng-if="data.status==verified">
<span class="span-outer">
{{ data.status }}
{{ data.name }}
</span>
</div>
Here is the data that I get from the URL I am using in app.js:
{
"message":"Request Successful",
"data":{
"id":"x4vqAl",
"name":"300 Suns Brewing",
"description":"300 Suns Brewing was really just an idea brought up years ago, that kept surfacing every time a brewery was toured, a GABF was attended, a new craft beer was tasted, a bottle of homebrew was shared on the back deck in the cool summer evening air. It was just a dream and one day (gulp), we worked up the nerve to make it a reality. We wanted to put our time and our work into something that brought joy to others the way those moments brought joy to us. And we wanted to give our community very meaningful ways that they could become part of the shaping of our brewery.",
"website":"http:\/\/www.300sunsbrewing.com",
"established":"2014",
"isOrganic":"N",
"images":{
"icon":"https:\/\/s3.amazonaws.com\/brewerydbapi\/brewery\/x4vqAl\/upload_fI8k35-icon.png",
"medium":"https:\/\/s3.amazonaws.com\/brewerydbapi\/brewery\/x4vqAl\/upload_fI8k35-medium.png",
"large":"https:\/\/s3.amazonaws.com\/brewerydbapi\/brewery\/x4vqAl\/upload_fI8k35-large.png"
},
"status":"verified",
"statusDisplay":"Verified",
"createDate":"2014-05-05 12:24:15",
"updateDate":"2015-08-14 16:49:36"
},
"status":"success"
}
Very simple, but I can't even get it to load any data. The search input field is really irrelevant, but I included it in case that might be causing an issue.
You refer details as data in HTML. However, in the controller.js, you don't have any variable like $scope.data. So that's why you cannot load the data. In order to let HTMLor template can access the variable, you can declare the variable in $scope. (using $scope dot notation) format.
Because you are using $http().success() method, it returns you the data, so you don't do $scope.details = response.data, instead, you should do $scope.details = response;
Controller.js
function fetch(){
$http.get("https://api.brewerydb.com/v2/brewery/x4vqAl?key=cc12540abedfa669021307d4ba111d87&format=json")
.success(function(data) {
$scope.details = data;
});
} //end fetch
HTML
<div ng-if="details.status!=verified">
Loading results...
</div>
<div ng-if="details.status==verified">
<span class="span-outer">
{{ details.status }}
{{ details.name }}
</span>
</div>

Angularjs Div Show, Hide Toggle with adding class to active button

I'm new to this please bear with me
I'm trying to achieve div toggle and button class added when button clicked (active), i looked every where i been trying to do this for over 6 hours now :(.
here is my NAV div
<div id="sidebar-wrapper-button" ng-controller="Main">
<ul class="nav nav-pills">
<li ng-click="isInfo = !isInfo" ng-class="{'active':isInfo}"></li>
<li ng-click="isSetting = !isSetting" ng-class="{'active':isSetting}"></li>
</ul>
</div>
Content Div
<div ng-class="{'ng-show':isSetting,'ng-hide':!isSetting,'ng-hide':isInfo,}">
<h1>Setting</h1>
</div>
<div ng-class="{'ng-show':isInfo,'ng-hide':!isInfo,'ng-hide':isSetting}">
<h1>Info</h1>
</div>
app.js
//toggle Setting
app.controller('Main', function($scope) {
$scope.isSetting = false;
});
//toggle Info
app.controller('Main', function($scope) {
$scope.isInfo = false;
});
Thank you.
If I understood your request right, here's what I would do:
var app = angular.module('myApp', []);
app.controller('Main', function($scope) {
$scope.tabActive = null; // here insert 1, 2 or null depending on what the initial selection should be
});
li a{text-decoration: none;}
<link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="container" ng-app="myApp">
<div ng-controller="Main">
<ul class="nav nav-pills">
<li ng-click="tabActive = 1" ng-class="{'active':tabActive == 1}">
</li>
<li ng-click="tabActive = 2" ng-class="{'active':tabActive == 2}">
</li>
</ul>
<div ng-show="tabActive == 1">
<h1>Info</h1>
</div>
<div ng-show="tabActive == 2">
<h1>Setting</h1>
</div>
</div>
</div>
Simpler way is to use angular expression {{}} to output appropriate string:
<h1>{{isSetting ? 'Setting' : 'Info'}}</h1>
Requires less markup and less class change logic code and ultimately less scope watches

Resources