I have a button which I want to toggle with ng-show based on the value of my Id.
in my javascript I call my service from on function and then using them from another function.
My issue is when using ng-click I can return the correct Id but when using ng-init it returns the value as undefined.
how do I Invoke and define the Id value from a "onload" event like ng-init?
HTML
<button type="button" class="col button button-small button-dark" ng-click="showMe(ph);" ng-init="showMe(ph);">
Check In
</button>
Javascript
Service Get
$scope.PhaseData = function(Truck) {
var TruckID = window.localStorage['truckid'];
$http.get("http://localhost:53101/TruckService.svc/GetStatusA/" + TruckID)
.success(function(data) {
var PhaseID = null;
var obj = data;
var ar = [];
angular.forEach(obj, function(index, element) {
angular.forEach(index, function(indexN, elementN) {
ar.push({PId: indexN.PId, PhaseId: indexN.fk_Phase, Checkin: indexN.Checkin, Chassis: indexN.ChassisPrep, Floor: indexN.Floor, Body: indexN.Body, Paint: indexN.Paint, PhaseName: indexN.PhaseName });
$scope.ph = ar;
/* $scope.PHID = 1; indexN.PId*/
})
});
})
.error(function(data) {
console.log("failure");
})
};
function
$scope.showMe = function(ph)
{
console.log('2', $scope.ph[0].PId );
console.log('cool');
if ($scope.ph[0].PId >= 1)
{
$scope.show=true;
}
else if($scope.ph[0].PId <= 2)
{
$scope.show=false;
}
}
Change your code to this, may be your HTML render before the value is coming
<button ng-if="ph" type="button" class="col button button-small button-dark" ng-click="showMe(ph);" ng-init="showMe(ph);">Check In</button>
Related
I am new to JavaScript and kind of stuck at this place
function onView(data){
var item_size = data;
return item_size;
}
I have this function with parameter passing through HTML input, i want to use return of this function in another function
function onRegisterInput(){
var y= onView(data);
}
onRegisterInput is called onclick Button, i want to take return value of onView function as var y.
How can i do this ??
Everytime i click button onRegisterInput() function is called but my debugger shows data is undefined. Please help. Thanks in advance.
As you can see in onView, it takes data as function parameter, however you don't give it any parameter in your call var y= onView();. From my understanding, onView get's triggered when a button is clicked, so I'd suggest you save your value in a global variable so you can use it across functions
There are 2 ways for you to get the data in your button click callback.
Get data from the DOM
There are different ways to keep data inside the DOM, but data-* attributes are popular:
function testMe(event, button) {
const magicNumber = button.getAttribute('data-magic-number');
document.getElementById('result1').innerHTML = magicNumber;
}
function testMe2(event, button) {
const magicNumber = document.getElementById('magic2').getAttribute('data-magic-number');
document.getElementById('result2').innerHTML = magicNumber;
}
.test {
padding: 4px;
}
<div class="test">
<button id="button1" data-magic-number="123456789" onclick="testMe(event, this)">Button 123456789</button>
<div id="result1"></div>
</div>
<div class="test">
<span data-magic-number="987654321" id="magic2">Click this: </span><button id="button2" onclick="testMe2()">Button 987654321</button>
<div id="result2"></div>
</div>
Another option is to keep data inside the JS
let myMagicNumber = 1;
let resultDiv = document.getElementById('result');
function showNumber() {
resultDiv.innerText = myMagicNumber;
}
function incNumber() {
myMagicNumber++;
showNumber();
}
function decNumber() {
myMagicNumber--;
showNumber();
}
<div>
<button onclick="showNumber()">Show</button>
<button onclick="incNumber()">+1</button>
<button onclick="decNumber()">-1</button>
</div>
<div id="result">
</div>
Let's return to your example
function onView(data) {
// Some data processing
// We will return data length for example
return (typeof data === 'string' ? data.length : 0);
}
function onRegisterInput() {
// Button click
let data = document.getElementById('name').value;
if (data != '') {
var y = onView(data);
document.getElementById('result').innerText = 'Name: ' + data + ', length: ' + y;
} else {
document.getElementById('result').innerText = 'Enter your name';
}
}
<div>
<label>Name: <input type="text" id="name"/></label>
<button onclick="onRegisterInput()">Register</button>
</div>
<div id="result"></div>
Is there a way to simplify the below code by using an array? For example, when button 1 (with the index of 0) in the HTML is clicked, could that be used to get a value at index 0 in another array?
function f1() {
document.getElementById("dis").innerHTML = "JoeMae";
}
function f2() {
document.getElementById("dis").innerHTML = "TanakaMae";
}
function f3() {
document.getElementById("dis").innerHTML = "James";
}
function f4() {
document.getElementById("dis").innerHTML = "Deus";
}
<button onclick="f1()">no.1</button>
<button onclick="f2()">no.2</button>
<button onclick="f3()">no.3</button>
<button onclick="f4()">no.4</button>
<p id="dis"></p>
You can simplify without using array:
<button onclick="f('JoeMae')">no.1</button>
<button onclick="f('TanakaMae')">no.2</button>
<button onclick="f('James')">no.3</button>
<button onclick="f('Deus')">no.4</button>
<p id="dis"></p>
function f(str) {
document.getElementById("dis").innerHTML = str;
}
Use another array such that the nth index of that array corresponds to the nth button:
const texts = [
"JoeMae",
"TanakaMae",
"James",
"Deus"
];
const dis = document.getElementById("dis");
document.querySelectorAll('button').forEach((button, i) => {
button.addEventListener('click', () => {
dis.textContent = texts[i];
});
});
<button>no.1</button>
<button>no.2</button>
<button>no.3</button>
<button>no.4</button>
<p id="dis"></p>
Note that unless you're deliberately inserting HTML markup, you should probably use textContent, not innerHTML. (textContent is faster and safer)
Here's an approach that's vanilla JS. I used the dataset API to connect each button to its data, then a single handler to retrieve and display this data.
"use strict";
function byId(id){return document.getElementById(id)}
function newEl(tag){return document.createElement(tag)}
window.addEventListener('load', onLoaded, false);
function onLoaded(evt)
{
var responseArray = ['JoeMae', 'TanakaMae', 'James', 'Deus'];
responseArray.forEach( function(arrElem, elemIndex, arr)
{
var btn = newEl('button');
btn.textContent = `no.${elemIndex+1}`;
btn.dataset.response = arrElem;
btn.addEventListener('click', onClick, false);
document.body.appendChild(btn);
}
);
function onClick(evt)
{
let text = this.dataset.response;
byId('dis').textContent = text;
}
}
<p id='dis'></p>
Here's a slightly cleaner and more flexible example how to implement this type of functionality.
If you are having a lot of rendering functionality like this, I would recommend you to use a library/framework for it, though.
const buttonDefinitions = [
{title: 'no.1', name: 'Monica'},
{title: 'no.2', name: 'Erica'},
{title: 'no.3', name: 'Rita'},
{title: 'no.4', name: 'Tina'}
];
const buttonContainer = document.getElementById('buttonContainer');
const resultContainer = document.getElementById('resultContainer');
for (const buttonDefinition of buttonDefinitions) {
const button = document.createElement('button');
button.innerHTML = buttonDefinition.title;
button.onclick = () => {
resultContainer.innerHTML = buttonDefinition.name;
};
buttonContainer.appendChild(button);
}
<div id="buttonContainer"></div>
<div id="resultContainer"></div>
You can pass the element to the function and access the element data-attributes
In the below example I am passing data-name
function f(element) {
document.getElementById("dis").innerHTML = element.dataset["name"];
}
<button data-name="JoeMae" onclick="f(this)">no.1</button>
<button data-name="TanakaMae" onclick="f(this)">no.2</button>
<button data-name="James" onclick="f(this)">no.3</button>
<button data-name="Deus" onclick="f(this)">no.4</button>
<p id="dis"></p>
I am using Asp.MVC 5 for an application and I want to generate many checkboxes with different angularjs models, and I thought the best option is by using array model in angularjs. I tried the code below inside a foreach:
#{
int i = 0;
foreach (var selectedVesselViewModel in Model.SelectedVesselViewModels)
{
using (Html.BeginForm("SelectNotificaiton", "Admin", new { area = "DashBoard" }, FormMethod.Post, new { id = "filterVesselsForm_" + i}))
{
#Html.HiddenFor(item => selectedVesselViewModel.VesselId, new {ng_model= "SelectedVessels[" + i + "].VesselId" })
<li class="row">
<div class="col-md-10">
<a href="#" class="text-admin-area">
#selectedVesselViewModel.VesselName
</a>
</div>
<div class="col-md-2">
<div class="pull-right">
<div class="checkbox checkbox-inline">
#Html.CheckBoxFor(item => selectedVesselViewModel.Selected,
new {id = "SelectedVesselViewModels_"+i+"__Selected",
onchange ="document.getElementById('filterVesselsForm_"+i+"').submit()",
ng_model = "SelectedVessels[" + i + "].Selected"
})
<label for="SelectedVesselViewModels_#(i++)__Selected"></label>
</div>
</div>
</div>
</li>
}
}
}
i variable is an incrementing variable:
in the angularjs controller I have something like this:
(function (app) {
"use strict";
app.controller("DashboardCtrl", ['$scope',
function ($scope) {
function init() {
// $scope.SelectedVessels = [];
}
$scope.SelectedVessels = [];
init();
$scope.RefreshSideBarVessels = function() {
angular.forEach($scope.SelectedVessels, function (value, key) {
alert($scope.SelectedVessels[key].VesselId);
});
}
}]);
})(adminModule);
When I use angularjs foreach loop the $scope.SelectedVessels seems to be empty but I dont know why!
angular.forEach($scope.SelectedVessels, function (value, key) {
alert($scope.SelectedVessels[key].Selected);
});
Does anybody know where is the problem, why I cant access the inner properties of the $scope.SelectedVessels array and why it is empty ?
How you are adding values to your array ie. $scope.SelectedVessels is important
Please have a look at below example.
var values = {name: 'Raja', gender: 'male'};
var log = [];
angular.forEach(values, function(value, key) {
this.push(key + ': ' + value);
}, log);
expect(log).toEqual(['name: Raja', 'gender: male']);
Here is the solution to this problem:
I had to use ng-init to each checkbox to instantiate the ng-model.
#Html.CheckBoxFor(item => selectedVesselViewModel.Selected,
new {id = "SelectedVesselViewModels_"+i+"__Selected",
onchange ="document.getElementById('filterVesselsForm_"+i+"').submit()",
ng_model = "SelectedVessels[" + i + "].Selected",
ng_init = "SelectedVessels[" + i + "].Selected="+ selectedVesselViewModel.Selected.ToString().ToLower()
})
First off , its ng-model not ng_model (- vs _) but that could be typo.
Second, try this code
$scope.onChange = function (index, value) {
$scope.SelectedVessels[index] = value;
}
#Html.CheckBoxFor(item => selectedVesselViewModel.Selected,
SelectedVessels[i] = selectedVesselViewModel.Selected
new {id = "SelectedVesselViewModels_"+i+"__Selected",
onchange ="document.getElementById('filterVesselsForm_"+i+"').submit()",
ng-model = "SelectedVessels[" + i + "].Selected",
on-change="onChange(i,selectedVesselViewModel.Selected)
})
I'm new to AngularJS, so sometimes when I do some mistake that is obvious, I still can't figure out what is going wrong with my code. So saying, here is my doubt:
HTML code:
<body ng-controller = "Ctrl">
<script id="Page6.html" type="text/ng-template">
<div class="list card" style="background-color: beige">
<div class="item item-icon-left">
<i class="icon ion-home"></i>
<input type="text" placeholder = "Enter display name" ng-model="user.nam">
</div>
<a ng-click = "saveedit(user)"<button class="button button-clear">SAVE DETAILS</button></a>
</div>
</script>
</body>
CONTROLLER.JS
.controller('Ctrl',function($scope,$rootScope,ContactService){
$rootScope.saveedit=function(user) {
ContactService.save({names: user.nam, image:"images.jpg"},ContactService.getid("Donkey"));
}
});
THIS IS THE SERVICE:
.service('ContactService', function () {
var items = [
{ id: 1, names: 'Dolphin', image: 'dolphin.jpg',}, { id: 2, names: 'Donkey', image: 'donkey.jpg'}, { id: 3, empid: 'FG2043', image: 'penguin.jpg'}];
var im = [{image: ''}];
var ctr=0;
var uid=3;
this.save = function (contact,id) {
ctr=0;
for (i=0;i<items.length;i++) {
if(items[i].id == id)
{
im[0].image= items[i].image;
ctr=100;
break;
}
}
uid = (uid+1);
contact.id = uid;
items.push(contact);
if (ctr==100 ) {
alert("in save putting the image");
items[contact.id].image = im[0].image; //doubt
alert("finished putting image");
}
}
//simply search items list for given id
//and returns the object if found
this.getid = function (name) {
for (i=0;i<items.length;i++) {
if (items[i].names == name) {
return (i+1);
}
}
}
//simply returns the items list
this.list = function () {
return items;
}
});
The problem I am facing is this: Everything works, except one thing. In ContactService, push() function, the line I have commented as //doubt is not getting executed.
The alert before it "in save putting the image" runs, but the alert "finished putting image" doesn't. What is the mistake there??
The problem here is that you're using the id's, which start at 1, to navigate in an array whose indexes start at 0.
To access the most recently pushed element, you should rather do :
items[contact.id - 1].image = im[0].image;
But you actually don't need to access the array : items[contact.id - 1] will return the object that you just pushed, and which is already referenced by variable contact, so you could just do :
contact.image = im[0].image;
I am not so good at JS, but I am trying to add dynamically a row with content (clone). This is working, IF I put
var apcount = 0;
function add(id, apmax) {
var aptable = id;
if (apmax > apcount) {
$("table tr:last").clone().appendTo("#m1s1t2").find(':input').attr('name', function(index, name) {
return name.replace(/(\d+)$/, function(fullMatch, n) {
return Number(n) + 1;
});
})
}; apcount++;
}
the 'id' direct into '.appendTo'. The call of this function is a button
<input onclick="add('m1s1t2',2)" type="button">
Actually I want to have something like '.appendTo(id)'
Anyone an idea?
So use the id variable you pass in
change
.appendTo("#m1s1t2")
to
.appendTo("#" + id)