I'm currently displaying a list of operations that the user can invoke in a dropdown menu.
I want to display all the information related to an operation the moment you click on it.
I've got this so far:
app.controller('selectAll', ['$http', '$scope' , '$rootScope', function ($http, $scope, $rootScope) {
$scope.response;
$scope.operations;
$scope.operationDetails;
$rootScope.$on("invokeSelectAll", function(){
$scope.invokeSelectAll();
});
$scope.invokeSelectAll = function(){
$scope.response = $http.post('/invoke/selectAll/', $rootScope.dataObj);
$scope.object = $rootScope.object;
$scope.response.then(function(data) {
$scope.responses = data.data ? data.data : "Select Operation not supported on this bean";
});
};
$scope.getOperation = function (operation) {
$scope.operationDetails = operation;
console.log(operation);
}
}]);
<div ng-controller="selectAll">
<div align="left">
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">
Choose operation
<span class="caret"></span></button>
<ul class="dropdown-menu">
<li ng-repeat="operation in object.operations">
<a href="#" ng-click="getOperation(operation)">
{{operation.name}}
</a>
</li>
</ul>
</div>
</div>
</div>
I'm using the getOperation(operation) function in html to send the operation object altogether in the javascript controller.
The operation object contains fields like description, return type and a list of parameters.
I want to display those fields when you click an operation from the dropdown menu.
Mentions: I use AngularJS 1.6.1
Any help would be much appreciated!
Try this.On button click call a function and set $scope.displayDropdown to true.And change <ul class="dropdown-menu" ng-if="displayOperation">
var app = angular.module('testApp', []);
app.controller('selectAll', ['$http', '$scope', '$rootScope', function($http, $scope, $rootScope) {
$scope.response;
$scope.operations;
$scope.operationDetails;
$scope.displayDropdown = false;
$scope.showDropdown = function() {
$scope.displayDropdown = true;
}
$rootScope.$on("invokeSelectAll", function() {
$scope.invokeSelectAll();
});
$scope.invokeSelectAll = function() {
$scope.response = $http.post('/invoke/selectAll/', $rootScope.dataObj);
$scope.object = $rootScope.object;
$scope.response.then(function(data) {
$scope.responses = data.data ? data.data : "Select Operation not supported on this bean";
});
};
$scope.getOperation = function(operation) {
$scope.operationDetails = operation;
console.log(operation);
}
}]);
.dropdown-menu {
padding:10px;
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="testApp" ng-controller="selectAll">
<div align="left">
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown" ng-click="showDropdown()">
Choose operation
<span class="caret"></span></button>
<ul class="dropdown-menu" ng-if="displayDropdown">
<li ng-repeat="operation in object.operations">
<a href="#" ng-click="getOperation(operation)">
{{operation.name}}
</a>
</li>
</ul>
</div>
</div>
</div>
Related
how can i get a image id inside my controller while selecting on a image
My html file
<ul class="thumbnails">
<li class="span3" ng-repeat="reward in rewardData.results">
<a class="thumbnail" href="#">
<img src="data:image/png;base64,{{reward.image}}" />
</a>
</li>
</ul>
<div style="display:block;width:60%;">
Save Challenge and Continue
</div>
it will show multiple images, i want a image id inside my controller while some one select any image, can anyone know how to implement it?
my controller :
app.controller("PrizesController", ["$location", "$scope","authenticationSvc","$http", function ($location, $scope,authenticationSvc, $http) {
console.log("inside prize controller");
var token = authenticationSvc.getUserInfo();
var config = {
headers: {
'h5cAuthToken': token.accessToken,
'Accept': 'application/json;odata=verbose'
}
};
$http.get("http://IPandPortnumber/ccp-services/challengereward/allRewards", config)
.then(function (response) {
$scope.rewardData = response.data;
});
$scope.selectPrizes = function () {
// some block of codes
$location.path("/invite");
}
}]);
Pass the image id to getImgId(reward.id) function
<ul class="thumbnails">
<li class="span3" ng-repeat="reward in rewardData.results">
<a class="thumbnail" href="#">
<img src="data:image/png;base64,{{reward.image}}" ng-click="getImgId(reward.id)"/>
</a>
</li>
</ul>
<div style="display:block;width:60%;">
Save Challenge and Continue
</div>
//inside controller
$scope.getImgId= function (id) {
console.log(id);
}
Try this inside your controller
$scope.imgId='';
$scope.getImgId= function (id) {
console.log(id);
$scope.imgId=id;
}
$scope.selectPrizes = function () {
// You will get selected img id here
console.log($scope.imgId);
$location.path("/invite");
}
I have a view which does a for each loop over a list of database items. I am looking to have a "Details" action for each one which opens a modal passing the id for each item into it and displays the details for that item in a partial view within that modal.
So far I have the following
#foreach (var item in Model)
{
Details
}
<div class="modal fade" id="detailsModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
#{Html.RenderAction("_PartialDetails", "ActivityAds", new { #id = "NEED TO PASS ID HERE" });}
</div>
</div>
</div>
</div>
I am trying to avoid putting the modal in the for each loop as I fear that would be very inefficient having to create a modal for every record. I could be calling the partial view in the Modal wrong as well. I am out of practise Im afraid and I am sure there is a way to do this
Thank you
One way would be to use ajax to fill in the container dynamically.
here is an example from an app i have - note that some of the javascript is in an external js file so can't directly use model; model values are stored in hidden fields and/or data-id, data-value attributes for this purpose
#foreach (var assignment in Model.Assignments)
{
<li role="presentation" id="assignmentsDetails_#assignment.AssignmentView.AssignmentViewId" data-id="#assignment.AssignmentView.AssignmentViewId">
<a role="menuitem" onclick="selectCriteria(this);" title="#assignment.AssignmentView.AssignmentViewDescription">Criteria #criteriaNumber</a>
</li>
criteriaNumber++;
}
javascript
function selectCriteria(clickedElement) {
var dataid = $(clickedElement).parent().attr("data-id");
loadAssignmentDetails(dataid);
}
function loadAssignmentDetails(assignmentViewId) {
$.ajax({
type: "GET",
url: Config.RootUrl + "Assignments/Detail/" + assignmentViewId + "/" + $("#AssignmentTypeValueId").val(),
success: function (data) {
$("#assignmentViewDetailsContainer").html(data);
}
});
}
Here is my solution based "Nikki9696" answer :) It works perfectly. Thank you very much! Nikki9696
function showDetails(clickedElement) {
var dataid = $(clickedElement).attr("data-id");
showDetailsAjax(dataid);
}
function showDetailsAjax(activityAdID) {
var link = '#Url.Action("_PartialDetails", "ActivityAds", new { id = "-1"})'
link = link.replace("-1", activityAdID);
$.ajax({
type: "GET",
url: link,
error: function(data)
{},
success: function (data) {
$("#detailsModal .modal-body").html(data);
$('#detailsModal').modal('show');
},
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="modal fade" id="detailsModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body"></div>
</div>
</div>
</div>
#foreach (var item in Model)
{
<a onclick="showDetails(this);" id="activityAdDetails_#item.ad_id" data-id="#item.ad_id">Details</a>
}
I have an alternative, similar but different enough that I thought it worth sharing - I wanted to use unobtrusive jquery to achieve the same thing through attribute mark up only, so I define a separate partial view for the modal and it's script, and include it in my layout page, so that in each other view all I need to do is add markup to use the modal and functionality I built into that partial script. I've added functionality to the modal to allow me to specify a script to call when the modals submit is successful, etc. The dialog content is retrieved from the server (by calling a controller method that returns a partial view - hence the need to disable ajax cache). Heres an example outside of a list which calls the javascript RefreshAll when done:
<button class="btn btn-sm btn-success completeFixtureButton"
data-submittext="Update"
data-modalsubmit="CompleteFixtureForm"
data-modaltitle="Fixture Completed"
data-modalsuccess="RefreshAll();"
data-modalload="#Url.Action("FixtureCompleted", new { fixtureId = fix.Id })">
and here's a similar example but from a link styled as a button instead of a button:
<a class="btn btn-default" href="#"
data-modalsubmit="editLeagueForm"
data-modaltitle="Edit Season"
data-modalsize="lg"
data-modalload="#Url.Action("EditLeaguePartial", "League", new { leagueId = Model.Season.League.Id, seasonId = Model.Season.Id })"><span class="glyphicon glyphicon-white glyphicon-cog"></span>Season Settings</a>
Heres one within a list/table:
<tbody id="clubList">
#foreach (Player p in Model.Club.Players.OrderBy(p => p.LastName))
{
bool playerManager = Model.Club.Managers.Any(m => m.Id == p.Id);
<tr>
<td>
<a href='#' data-modaltitle="#p.FullName" data-modalload="#Url.Action("ContactPlayerPartial", "Player", new { playerId = p.Id })">
<img src="#Url.Action("ProfilePictureById", "Player", new { playerId = p.Id })" style="max-width:3em; margin-right:10px;" class="pull-left" /> #p.FullName
</a>
</td>
</tr>
...
}
and here's the modal partial (_ModalDialogPartial.cshtml) in the Shared Views folder:
<div id="details" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h2 id="detailsHeader"></h2>
</div>
<div class="modal-body">
<div id="detailsBody" ></div>
</div>
<div class="modal-footer">
Close
<input type="submit" id="btnModalSave" class="btn btn-primary" value="Save"/>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$.ajaxSetup({ cache: false });
initialiseModals();
});
function initialiseModals() {
$('#details').on('shown.bs.modal', function () {
$.validator.unobtrusive.parse($('#details'));
});
$(document).on('click', '*[data-modalload]', function () {
var e = $(this);
if (e.data('submittext') != undefined) {
$('#btnModalSave').html(e.data('submittext'));
} else $('#btnModalSave').html('Save');
if (e.data('class') != undefined) {
var cls = e.data('class');
$('#details').removeClass(cls).addClass(cls);
}
if(e.data('modalsize') != undefined) {
var size = e.data('modalsize');
$('.modal-dialog').addClass('modal-' + size);
}
if (e.data('modalsubmit') == undefined) {
$('#btnModalSave').hide();
$('#btnModalCancel').addClass("btn-primary");
}
else {
$('#btnModalSave').show();
$('#btnModalCancel').removeClass("btn-primary");
$('#btnModalSave').unbind('click').click(function (ctrl) {
$('#btnModalSave').attr('disabled', 'disabled');
ctrl.preventDefault();
var submitUrl = $('#' + e.data('modalsubmit')).attr("action");
var formData = $('#' + e.data('modalsubmit')).serialize();
$.post(submitUrl,
formData,
function (data, status, xhr) {
$('#btnModalSave').removeAttr('disabled');
$('#details').modal('hide');
if (e.data('modalsuccess') != undefined) {
eval(e.data('modalsuccess'));
}
}).error(function () {
$('#btnModalSave').prop('disabled', false);
});
});
}
$('#detailsBody').load(e.data('modalload'), function () {
$('#detailsHeader').html(e.data('modaltitle'));
$('#details').modal('show');
$.validator.unobtrusive.parse($('#detailsBody'));
});
});
}
</script>
I am new to angularjs and I am trying to display two function values on page loading.
I am able to load only one function.
When i try to load two methods only first init method is loading.
Then i try to declare a common function "data-ng-init="initializeMethods()" in html but I am not able to get any value.
My html page
I used common init function name as "data-ng-init="initializeMethods()".
<div class="container-fluid text-center" ng-controller="UserDataController as ctrl" data-ng-init="initializeMethods()">
<div class="row content">
<div class="col-sm-2 sidenav">
<div class="well well-lg col-xs-30" style="background-color: green;" ng-show="true">
<img class="img-responsive" style="padding-bottom:10px;" src="css/images/image.jpg" />
<div class="form-group">
<select class="form-control" ng-model="model.selectedValue" name="groupzname">
<option ng-repeat="item in model.dropDownData track by $index" value="{{item}}">{{item}}</option>
</select>
</div>
</div>
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav">
<li><span class="glyphicon glyphicon-dashboard vmenu"></span>Dashboard
</li>
<li class="#/Profile"><span class="glyphicon glyphicon-user vmenu"></span>Profile
</li>
<li><span class="glyphicon glyphicon-edit vmenu"></span>Account
</li>
<li><span class="glyphicon glyphicon-tags vmenu"></span>Dropbox
</li>
<li><span class="glyphicon glyphicon-off vmenu"></span>Checklist
</li>
<li><span class="glyphicon glyphicon-off vmenu"></span>Report
</li>
<li><span class="glyphicon glyphicon-off vmenu"></span>Settings
</li>
<li><span class="glyphicon glyphicon-off vmenu"></span>Help
</li>
</ul>
</div>
</div>
<div class="col-sm-8 text-left" ng-show="true">
<h1>Welcome</h1>
<div class="form-group">
<label class="form-control" ng-model="model.membervalue" name="membername" style="border:none"> {{model.membervalue}}</label>
</div>
</div>
</div>
<div class="col-sm-4">
<div class="panel panel-primary">
<div class="panel-heading"><img src="css/images/Birthday.png" />BIRTHDAYS TODAY</div>
<div class="panel-body">
<ul>
<li ng-repeat="data in displayBirthdays">{{data}}</li>
</ul>
</div>
</div>
My Controller
Here the common function " $scope.initializeMethods = function(){" which contains two different functions in it are "$scope.getDisplayList = function(){" and "$scope.Birthdays = function(data){"
$scope.initializeMethods = function(){
$scope.getDisplayList = function(){
$scope.model.dropDownData = [];
console.log(displaynames);
for(var i=0; i<displaynames.length; i++)
{
$scope.model.dropDownData.push(displaynames[i].groupzname + " - "+displaynames[i].membername + " - "+displaynames[i].membercode); // we can itterate and set the drop down values
console.log($scope.model.dropDownData);
$scope.model.selectedValue =displaynames[i].groupzname + " - "+displaynames[i].membername + " - "+displaynames[i].membercode; // set model value
$scope.model.memberName = displaynames[i].membername;
}
$window.localStorage.x = $scope.model.dropDownData; //setting data in cookies
}
$scope.Birthdays = function(data){
var current_date = moment().format('YYYY-MM-DD');
var date_time = current_date + " 00:00:00";
var json = {
"json": {
"request": {
"servicetype": "21",
"functiontype": "2021",
"memberid": $rootScope.displayList[0].memberid,
"groupzcode": $rootScope.displayList[0].groupzcode,
"date":date_time,
"country": [
"India"
],
"state": [
"_ALL"
],
"city": [
"_ALL"
],
"segment": [
"_ALL"
],
"groupzlist":[
$rootScope.displayList[0].groupzcode
], "session_id":$rootScope.displayList[0].session_id,
}
}
}
UserService.Birthdays(json).then(function(response){
//callback(response);
var show_birthdays = [];
console.log("displayBirthdays");
if (response.json.response.statuscode != 0 && response.json.response.statusmessage !='Success') {
show_birthdays = response.json.response.statusmessage;
console.log("show_birthdays "+show_birthdays);
}else {
console.log("Greeting response: "+response);
var resp = response;
var greetings = resp.json.response.greetings;
console.log(greetings);
console.log(show_birthdays);
}
});
}
}
can anyone please tell me how I can display both function values on page loading.
Thanks in advance.
This is written in ES6, but you get the gist.
export default class MyController {
constructor() {
super(arguments);
this.MakeInitCall();
}
MakeInitCall() {
// Your initialisation code here, gets called on controller (page) start;
this.getDisplayList();
this.Birthdays(data);
}
getDisplayList() {
$scope.whatevervariable = 'foo';
}
Birthdays(data) {
$scope.anothervariable = 'bar';
}
}
You could rewrite for ES5 etc.,
Actually your initializeMethods function just declare your getDisplayList and Birthdays functions. If you call both of them at the end of the initializeMethods, it should work:
$scope.initializeMethods = function(){
$scope.getDisplayList = function(){...}
$scope.Birthdays = function(){...}
$scope.getDisplayList();
$scope.Birthdays();
}
Controller:
$scope.initializeMethods = initializeMethods;
$scope.getDisplayList = getDisplayList;
$scope.birthdays = birthdays;
// Init function when page load
$scope.initializeMethods();
function initializeMethods () {
$scope.getDisplayList();
$scope.birthdays();
}
function getDisplayList () {
// something
}
function birthdays () {
// something
}
I was searching for the solution, but can't resolve it.
I have HomeController and in its constructor I make some functions to work with firebase items. The list group displays todos and buttons, which are connected with data state. The code below shows the todo directive. I'm using scope to exchange the data.
ToDo App
Add Task
<!-- Task List Starts Here -->
<ul class="list-group" ng-show="!isLogged">
<li class="list-group-item clearfix message" ng-repeat="message in messages | filter: {mail : email}" ng-class="{disabled: ! message.done }">
<p class="lead">{{message.text}}</p>
<div>
<span class="pull-right">
<button class="btn btn-default btn-xs"><span class="glyphicon glyphicon-pencil"
ng-click="editTask(message)"></span></button>
<button class="btn btn-primary btn-xs" ng-show="! message.done"><span class="glyphicon glyphicon-ok" ng-click="doneTask(message)"></span></button>
<button class="btn btn-primary btn-xs" ng-show="message.done"><span class="glyphicon glyphicon-repeat" ng-click="unDoneTask(message)"></span></button>
<button class="btn btn-danger btn-xs"><span class="glyphicon glyphicon-remove" ng-click="deleteTask(message)"></span></button>
</span>
</div>
</li>
</ul>
<!-- Task List Ends Here -->
</div>
And then I have main.controller file
export default class MainController {
constructor($scope, $firebaseArray, $firebaseAuth) {
var ref = new Firebase("https://learn11.firebaseio.com/todos");
$scope.messages = $firebaseArray(ref);
$scope.addMessage = function() {
$scope.messages.$add({
text: $scope.newMessageText
});
};
$scope.isLogged = false
$scope.loginUser = function() {
ref.authWithPassword({
email: $scope.email,
password: $scope.password
}, function(error, authData) {
if (error) {
$scope.isLogged = false
console.log("Login Failed!", error);
}
else {
$scope.isLogged = true
console.log($scope.isLogged)
}
});
};
$scope.addTask = function() {
var message_ref = new Firebase('https://learn11.firebaseio.com/todos');
var newMessageRef = message_ref.push();
newMessageRef.set({
'done': true,
'text': $scope.task,
'mail': $scope.email
});
};
$scope.editTask = function(message) {
$scope.task = $scope.messages[index].text;
console.log($scope.messages[index].text);
$scope.editIndex = index;
}
$scope.doneTask = function(message) {
$scope.messages[index].done = true;
}
$scope.unDoneTask = function(message) {
$scope.messages[index].done = false;
}
$scope.deleteTask = function(message) {
console.log(message)
$scope.messages.$remove(message)
}
}
}
Can you please help me? What can I do to make it work? And also do you know why isLogged state is not changed in view while it has changed in controller?
Try to use $scope.$apply(function () {$scope.isLogged = true}) for changing isLogged.
Is it possible to access child elements within a button that has a specific class? There will be multiple buttons created. When a submit button is clicked, I want to iterate through the list of 'btnSelection' buttons created and if a 'btnSelection' button has the 'active' class, I want to push the span data into an array.
I imagine I'd need the parameters put into an object that itself will be a parameter going into the submit method on ng-click, but I'm not sure exactly how to write the Angular portion. Searching Google doesn't yield any specific examples. I'd appreciate any help.
Example HTML:
<div ng-repeat="item in items">
<button id="btnSelection" class="active">
<span>{{item.value}}</span>
</button>
</div>
<button ng-click="submit()">Submit</button>
You shouldn't use an active class in you're controller, it's not the angular way. Instead use an active attribute in your items objects and set your active class afterward.
Here is a jsFiddle:
http://jsfiddle.net/L5z3j0gj/2/
HTML:
<div ng-app='myApp' ng-controller='myController'>
<div ng-repeat="item in items">
<button type='button'
ng-click='addContent($index)'
ng-class="{active: item.active}"
ng-disabled='!item.active'>
<span>{{item.value}}</span>
</button>
</div>
<button type='button' ng-click='addContents(items)'>Submit</button>
{{contentsArray}}
</div>
Controller:
angular.module('myApp', [])
.controller('myController', function($scope) {
$scope.items = [
{ value: 'value1', active: true },
{ value: 'value2', active: false },
{ value: 'value3', active: true }
];
$scope.contentArray = [];
$scope.addContent = function(index) {
console.log($scope.items[index]);
$scope.contentArray.push($scope.items[index].value);
};
$scope.addContents = function(items) {
$scope.contentsArray = [];
for (var idx in items) {
var item = items[idx];
if (item.active) {
$scope.contentsArray.push(item.value);
}
}
};
});
CSS:
.active {
background: green;
}
Demo: http://jsfiddle.net/bjbrc5wy/3/
<div ng-controller="ItemCtrl">
<ul>
<li ng-repeat="item in items">
<button ng-click="toggleActive(item)" class="active-{{item.active}}">
{{item.val}}
</button>
</li>
</ul>
<br>
<button ng-click="submit()">Submit</button>
</div>
You need to use a controller which acts as a parent object, a container for children. Then when you press your submit button from within this controller, you can access other items from the same controller $scope. You can see I also tie my data to the CSS with class="active-{{btn.active}}", so it automatically updates according to its active status. The controller is defined like so:
function ItemCtrl($scope) {
$scope.items = [ // sample data
{val:1, active:true},
{val:2, active:false}];
$scope.submit = function() {
var arr = [];
angular.forEach($scope.items, function(item) {
if(item.active) arr.push(item.val);
});
alert(arr); // here's the array of item values
};
}