I have the following html:
<div ng-show=showMarketingNav>
...
</div>
<div ng-show=showProductsNav>
...
</div>
<div ng-show=showSettingsNav>
...
</div>
What I want to do is to easily be able to hide all but one of the divs from another controller. I thought I could be clever and do the following:
var subNavMenuDisplays = {
Marketing: $scope.showMarketingNav,
Products: $scope.showProductsNav,
Settings: $scope.showSettingsNav
}
$rootScope.hideContextMenu = function () {
for (var category in subNavMenuDisplays) {
subNavMenuDisplays[category] = false;
}
}
$rootScope.setContextMenu = function (name) {
$rootScope.hideContextMenu();
subNavMenuDisplays[name] = true;
}
but this obviously does not work as $scope.showMarketingNav etc. will be passed as value, not reference.
The following works, but is not exactly nice to work with:
$rootScope.hideContextMenu = function () {
$scope.showMarketingNav = false;
$scope.showProductsNav = false;
$scope.showSettingsNav = false;
}
$rootScope.setContextMenu = function (name) {
$rootScope.hideContextMenu();
if (name == "Marketing") {
$scope.showMarketingNav = true;
}
if (name == "Products") {
$scope.showProductsNav = true;
}
if (name == "Settings") {
$scope.showSettingsNav = true;
}
}
Is there a way to grab $scope.showMarketingNav by reference, or another clever way around this?
I'd prefer not using eval to concatenate variable names.
You can place an object on the $scope and then toggle it dynamically:
$scope.show = {};
$rootScope.setContextMenu = function (name) {
$scope.show = {};
$scope.show[name] = true;
}
And the Html:
<div ng-show="show.Marketing">
...
</div>
<div ng-show="show.Products">
...
</div>
<div ng-show="show.Settings">
...
</div>
Here's a plunker demonstrating the change.
You can assign simple updater functions in that object:
Marketing: function(val) { $scope.showMarketingNav = val },
Products: function(val) { $scope.showProductsNav = val},
Settings: function(val) { $scope.showSettingsNav = val}
Then call it:
subNavMenuDisplays[name](true);
Related
I'm building my little lib js.
my intent is to have both possibilities in this way:
//this:
core.find(".myclass").myAction (actor);
var target = core.target (".myclassname");
core.myAction (target, actor);
//or:
core.find(".myclass").myAction (actor);
var target = core.find(".myclassname");
core.myAction (target, actor);
//so, return the finded for core and gearcore, but
//I can not and I do not think it's feasible (is it?)
//this isn't a good solution... thanks.
//var target = core.find(".myclassname");
//target .myAction (target, actor);
anyway... the first is chained, the second part from the first class and generates the action through a parameter.
yes, I already know that I can create a copy of the functions, but it's disgusting ... and copy the target how can I solve it?
here it's about joining the two "find" or putting the two return or joining the two return or something else or maybe something similar.
for convenience: lib in jsfiddle else...
LIB:
note 1:the two eval functions are just a demo to get an answer. the complete lib contains more and I need to assign the target in both ways
class coregears {
constructor(gear) {
this.gear = gear;
}
actor(target, fname) {
alert("inside actor");
let t_, f_;
(1 == arguments.length) ? (t_ = this.gear, f_ = target) : (t_ = target, f_ = fname);
t_.forEach((looped) => { eval(f_)(looped); return this.gear});
}
}
class Core {
// return for core.function(target,actor);
target(subject)
{
let name;
var finded;
if (subject.startsWith(".")) {
name = subject.split(".")[1];
finded = [...document.getElementsByClassName(name)];
}
if (subject.match(/\B\#\w\w+\b/g)) {
name = subject.replace(/#(\S*)/g, 'ID_$1').split("ID_")[1];
finded = [...document.querySelectorAll("#" + name)];
}
if (subject.startsWith("[")) {
finded = [...document.querySelectorAll(subject)];
}
return finded;
}
// return for core.find(target).function(actor);
find(subject){
let name;
if (subject.startsWith(".")) {
name = subject.split(".")[1];
find = [...document.getElementsByClassName(name)];
}
if (subject.match(/\B\#\w\w+\b/g)) {
name = subject.replace(/#(\S*)/g, 'ID_$1').split("ID_")[1];
find = [...document.querySelectorAll("#" + name)];
}
if (subject.startsWith("[")) {
find = [...document.querySelectorAll(subject)];
}
return new coregears(find);
}
}
const core = new Core();
SCRIPT:
//chain
core.find(".test_Y").actor(myactor_1);
function myactor_1(looped) {
alert("actor_1");
looped.style = "font-weight: bold; color: magenta;";
};
//direct
var mytarget = core.target(".test_X");
core.actor(mytarget,myactor_2);
function myactor_2(looped) {
alert("actor_2");
looped.style = "font-weight: bold; color: green;";
};
HTML:
<div class="test_X">SIMPLE TEST CLASS</div>
<div class="test_X">SIMPLE TEST CLASS</div>
<div class="test_X">SIMPLE TEST CLASS</div>
<div class="test_Y">SIMPLE TEST CLASS</div>
<div class="test_Y">SIMPLE TEST CLASS</div>
<div class="test_Y">SIMPLE TEST CLASS</div>
Idea?
update: I replaced the eval with f_.call(this,looped); thank you #Shilly.
I'm trying to store the date and the data from an event source to an object containing the coreid and continue to push the data and date to the correct coreid object.
As of now it's storing the wifiData to both of the coreids instead of the corresponding one. How would I push the data to the right id?
<template>
<div class="container">
<h2>Probe Diagnostics</h2>
<div class="row">
<div class="col">
<line-chart id="wifiChart" ytitle="Signal Strength" label="Wifi Strength" :colors="['#b00']" :messages="{empty: 'Waiting for data'}"
:data="wifiData" height="250px" :library="{backgroundColor: '#eee'}" :download="true" :min="-20"
:max="20"></line-chart>
<column-chart :data="wifiData" ytitle="Signal Strength" height="250px"></column-chart>
</div>
<div class="col">
<line-chart :data="psSoc" ytitle="ps-soc" height="250px"></line-chart>
<line-chart :data="psVoltage" ytitle="ps-voltage" height="250px"></line-chart>
</div>
</div>
</div>
</template>
<script>
let wifiData = [];
let psSoc = [];
let psVoltage = [];
let photons = {};
export default {
data() {
return {
wifiData,
psSoc,
psVoltage,
photons,
}
},
mounted() {
this.streamData();
},
methods: {
streamData() {
// LIVE PUSH EVENTS
if (typeof (EventSource) !== "undefined") {
var eventSource = new EventSource(
"http://10.10.10.2:8020/v1/Events/?access_token=687b5aee0b82f6536b65f");
eventSource.addEventListener('open', function (e) {
console.log("Opened connection to event stream!");
}, false);
eventSource.addEventListener('error', function (e) {
console.log("Errored!");
}, false);
eventSource.addEventListener('WiFi Signal', function (e) {
var parsedData = JSON.parse(e.data);
if (parsedData.coreid in photons) {
photons[parsedData.coreid].push([parsedData.published_at, parsedData.data])
return
} else {
photons[parsedData.coreid] =[]
}
}, false);
eventSource.addEventListener('ps-soc', function (e) {
var parsedData = JSON.parse(e.data);
psSoc.push([parsedData.published_at, parsedData.data])
}, false);
eventSource.addEventListener('ps-voltage', function (e) {
var parsedData = JSON.parse(e.data);
psVoltage.push([parsedData.published_at, parsedData.data])
}, false);
}
}
}
}
</script>
Remove wifiData completely. Instead just manage the array directly inside the lookup object:
// Initialize if needed:
if(!photons[parsedData.coreid])
photons[parsedData.coreid] = [];
// Then push directly to it:
photons[parsedData.coreid].push(/*...*/);
I am fairly new to AngularJS and I have been reading some answers here but nothing worked out. I have a json file from a controller that I display in a select. I want to set the selected value based on the text value.This is what I have so far.
HTML:
<div ng-app="userModule" ng-controller="userCtrl">
<div class="row">
<div class="col-md-6">
<label>User Name:</label> <br />
<select ng-model="users.selectedUser" class="form-control" ng-options="item.UserName as item.UserName for item in users.availableOptions"></select>
</div>
Controller:
<script>
var _$http;
var _$scope;
var oldUser = #Html.Raw(Json.Serialize(ViewData["UserName"]));
var oldRole = #Html.Raw(Json.Serialize(ViewData["RoleName"]));
angular.module('userModule', [])
.controller('userCtrl', xConstructor);
function xConstructor($scope, $http) {
_$http = $http;
_$scope = $scope;
$http.get("/RoleManagement/GetUserData").then(xReceive);
$http.get("/RoleManagement/GetRoleData").then(roleReceive);
_$scope.submit = function () {
//alert("Here:" + _$scope.selectedUser);
$http.get("/RoleManagement/PutUserRoleData?UserId=" + _$scope.selectedUser.UserId + "&RoleId=" + _$scope.selectedRole.RoleId).then(writeSuccess);
}
}
function xReceive(userObject) {
_$scope.users = {
availableOptions: userObject.data,
**selectedUser: { UserId: oldId, UserName: oldUser } //What to put here?**
};
alert(JSON.stringify(JSON.stringify(_$scope.users.selectedUser));
}
</script>
Or any other suggestions on how to do this?
The problem is you are not mapping the model to any element in the array you have.
Assuming you have the id of the user you want to select this is what you do:
function xReceive(userObject) {
_$scope.users = {
availableOptions: userObject.data,
selectedUser: null
};
let selectedUser;
for (let i = 0; i < userObject.data.length; i++) {
if (userObject.data[i].id === oldId) {
selectedUser = userObject.data[i];
break;
}
}
if (selectedUser) {
_$scope.users.selectedUser = selectedUser;
}
alert(JSON.stringify(JSON.stringify(_$scope.users.selectedUser));
}
Also note, you can do this to just select the first one:
_$scope.users.selectedUser = _$scope.users.availableOptions[0];
I have the following issue for creating a object in Javascript
When a user clicks a button I want to push the sn_slab to the array slabs. But each serial_number is grouped by the batch_number.
The object should look something like this
var Object = {
'COFBP21018': {
slabs: {
0: 18765,
1: 38947,
...
}
},
'DEPOUS394O': {
slabs: {
0: 11006276,
1: 11020446,
...
}
},
..
}
my html looks like this
<a href=".." class="add_slab_to_array" data-batch_nr="COFBP21018" data-sn_slab="18765" />
<a href=".." class="add_slab_to_array" data-batch_nr="COFBP21018" data-sn_slab="38947" />
<a href=".." class="add_slab_to_array" data-batch_nr="DEPOUS394O" data-sn_slab="11006276" />
<a href=".." class="add_slab_to_array" data-batch_nr="DEPOUS394O" data-sn_slab="11020446" />
var block = {};
$('.add_slab_to_array').click(function(event) {
event.preventDefault();
var batch_nr = $( this ).attr('data-batch_nr');
var sn_slab = $( this ).attr('data-sn_slab');
// Create new object if batch_nr does not exists
// ADD sn_slab to Array inside the Object with related batch_nr
block[batch_nr] = {
slabs: [],
add: function(sn_slab) {
this.slabs.push(sn_slab)
}
}
block[batch_nr].add(sn_slab);
});
The code above works, but my array slabs is always overridden.
It seems to me you're redefining the block object each time you click. You should instead check if it's set before proceeding.
block[batch_nr] = block[batch_nr] || {};
block[batch_nr].slabs = block[batch_nr].slabs || [];
block[batch_nr].add = block[batch_nr].add || function(sn_slab) {
this.slabs.push(sn_slab);
};
Consider this
block[batch_nr] = {
slabs: [],
add: function(sn_slab) {
if (block[batch_nr]) {
block[batch_nr].slabs.push(sn_slab)
}
}
}
I have created an object where i need to assign some variables(parameters) and when the object is called, the variables(parameters) change. Here is my code:
var Modal = {
init: function () {
contact1: "";
contact2: "";
aboutus1: "";
aboutus2: "";
privacy1: "";
privacy2: "";
terms1: "";
terms2: "";
$(".modaltrigger").removeAttr("target");
$(".modaltrigger").click(function () {
if ($(this).is("#contact")) {
$('#primary_url').attr('href', contact1);
$('#secondary_url').attr('href', contact2);
} else if ($(this).is("#aboutus")) {
$('#primary_url').attr('href', aboutus1);
$('#secondary_url').attr('href', aboutus2);
} else if ($(this).is("#termsconditions")) {
$('#primary_url').attr('href', terms1);
$('#secondary_url').attr('href', terms2);
} else if ($(this).is("#privacy")) {
$('#primary_url').attr('href', privacy1);
$('#secondary_url').attr('href', privacy2);
}
});
}
};
I am trying to initialize the object above, and it does not work:
Modal.init(
contact1: "http:www.test1.com";
contact2: "http:www.test2.com";
aboutus1: "http:www.test3.com";
aboutus2: "http:www.test4.com";
privacy1: "http:www.test5.com";
privacy2: "http:www.test6.com";
terms1: "http:www.test7.com";
terms2: "http:www.test8.com"
);
it is Done like this way,
i Guess this is what you want to do.
var Modal = {
init: function (args) {
//then access your values like this
contact1= args.contact1;
contact2 = args.contact2;
..........
.........
.........
}
}
And to initiate this method you have write as
Modal.init({
contact1:"contact str",
contact2:"contact str",
.....
.....
lastitem : "last str"
});