Isolate just the element that was clicked - javascript

I'm just getting started with Angular and running up against some roadblocks in my understanding of certain core concepts. To better familiarize myself with this new framework I'm attempting to build a trivial application: "Would You Rather?". I present the user two questions, they pick one, I highlight their choice, and show how many votes each question has from previous users.
It sounds simple but I'm still stuck in a jQuery frame of mind; I want to select the element based on $(this) or $("#id").
I have a factory with an array of question objects. Each object has a firstQuestion and secondQuestion key that maps to a question, as well as a firstVotes and secondVotes key with the corresponding number of votes. I'm using a QuestionsCtrl to control scope and take action when a user makes a choice.
Here's my index.html file:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="utf-8">
<title>Would You Rather?</title>
<link rel="stylesheet" type="text/css" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div class="container" ng-app="wouldYouRatherApp">
<div ng-controller="QuestionsCtrl">
<div class="container">
<div class="row text-center">
<h1 class="col-md-12">Would you rather...</h1>
</div>
<div class="row text-center">
<div class="col-md-12">
<h2 class="btn btn-lg btn-{{buttonClass}}" ng-click="recordAnswer('first')">{{question.firstQuestion}}</h2>
<span class="badge" ng-show="badge.show">{{question.firstVotes}}</span>
</div>
</div>
<div class="row text-center">
<h3 class="col-md-12"><small>or</small></h3>
</div>
<div class="row text-center">
<div class="col-md-12">
<h2 class="btn btn-lg btn-{{buttonClass}}" ng-click="recordAnswer('second')">{{question.secondQuestion}}</h2>
<span class="badge" ng-show="badge.show">{{question.secondVotes}}</span>
</div>
</div>
<br>
<div class="row text-center">
<div class="col-md-12">
<h2 class="btn btn-lg btn-primary" ng-show="showNextQuestion" ng-click="nextQuestion()">Next Question <span class="glyphicon glyphicon-forward"></span></h2>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.3/angular.min.js"></script>
<script type="text/javascript" src="./main.js"></script>
</body>
</html>
And here's my main.js file:
var app = angular.module("wouldYouRatherApp", []);
app.factory("Badges", function() {
return {show: false}
})
app.factory("Questions", function() {
var Questions = [{
firstQuestion: "Ride a horse?",
firstVotes: 101,
secondQuestion: "Ride a cowboy?",
secondVotes: 212
},
{
firstQuestion: "Kiss a frog?",
firstVotes: 13,
secondQuestion: "Lick a slug?",
secondVotes: 23
},
{
firstQuestion: "Play Monopoly?",
firstVotes: 12,
secondQuestion: "Play Risk?",
secondVotes: 17
}];
return Questions;
})
app.controller("QuestionsCtrl", function($scope, Badges, Questions) {
$scope.question = Questions.shift();
$scope.buttonClass = 'default';
$scope.showNextQuestion = false;
$scope.badge = Badges;
$scope.recordAnswer = function(choice) {
console.log("User chose: " + choice);
$scope.buttonClass = 'success';
// increment votes badge
$scope[choice+'Votes'] += 1;
Badges.show = true;
$scope.showNextQuestion = true;
}
$scope.nextQuestion = function() {
$scope.question = Questions.shift();
Badges.show = false;
$scope.buttonClass = 'default';
$scope.showNextQuestion = false;
}
})
A live example can be found here: http://jsfiddle.net/t99TL/2/
The app's expected behavior is as follows:
Two questions are presented to the user.
The user clicks on one of the buttons.
That question is highlighted. And the votes badge is incremented. Both votes badges are displayed.
A 'Next Question' button is presented to the user.
When he/she clicks on the 'Next Question' button, a new question is loaded.
I feel like I probably need to create a directive for each individual question... but I'm not sure how to start, or if I'm even on the right path. Any advice on obstacles I'm going to face further down the line is much appreciated (i.e. Updating the votes attribute for the question, etc.).

There are a lot to change to make it work the way you want. This code is not perfect, just a demonstration.
HTML:
<div class="container" ng-app="wouldYouRatherApp">
<div ng-controller="QuestionsCtrl">
<div class="container">
<div class="row text-center">
<h1 class="col-md-12">Would you rather...</h1>
</div>
<div class="row text-center">
<div class="col-md-12">
<h2 class="btn btn-lg btn-{{question.firstQuestion.buttonClass}}" ng-click="recordAnswer(question.firstQuestion)">{{question.firstQuestion.text}}</h2>
<span class="badge" ng-show="badge.show">{{question.firstQuestion.votes}}</span>
</div>
</div>
<div class="row text-center">
<h3 class="col-md-12"><small>or</small></h3>
</div>
<div class="row text-center">
<div class="col-md-12">
<h2 class="btn btn-lg btn-{{question.secondQuestion.buttonClass}}" ng-click="recordAnswer(question.secondQuestion)">{{question.secondQuestion.text}}</h2>
<span class="badge" ng-show="badge.show">{{question.secondQuestion.votes}}</span>
</div>
</div>
<br>
<div class="row text-center">
<div class="col-md-12">
<h2 class="btn btn-lg btn-primary" ng-show="showNextQuestion" ng-click="nextQuestion()">Next Question <span class="glyphicon glyphicon-forward"></span></h2>
</div>
</div>
</div>
</div>
JS:
var app = angular.module("wouldYouRatherApp", []);
app.factory("Badges", function() {
return {show: false}
})
app.factory("Questions", function() {
var Questions = [{
firstQuestion: {
text:"Ride a horse?",
votes: 101,
buttonClass : 'default'
},
secondQuestion: {
text:"Ride a cowboy?",
votes: 212,
buttonClass : 'default'
},
},
{
firstQuestion: {
text:"Kiss a frog?",
votes: 13,
buttonClass : 'default'
},
secondQuestion: {
text:"Lick a slug?",
votes: 23,
buttonClass : 'default'
}
},
{
firstQuestion: {
text:"Play Monopoly?",
votes: 12,
buttonClass : 'default'
},
secondQuestion: {
text:"Play Risk?",
votes: 17,
buttonClass : 'default'
}
}];
return Questions;
})
app.controller("QuestionsCtrl", function($scope, Badges, Questions) {
$scope.question = Questions.shift();
$scope.buttonClass = 'default';
$scope.showNextQuestion = false;
$scope.badge = Badges;
$scope.recordAnswer = function(choice) {
choice.buttonClass = 'success';
choice.votes++;
Badges.show = true;
$scope.showNextQuestion = true;
}
$scope.nextQuestion = function() {
$scope.question.firstQuestion.buttonClass = "default";
$scope.question.secondQuestion.buttonClass = "default";
$scope.question = Questions.shift();
Badges.show = false;
$scope.showNextQuestion = false;
}
})
DEMO

Related

Conversation chat cannot submit

I have problem when make submit chat its have error 'handlebar is not define'. I follow tutorial code in this link : https://codepen.io/drehimself/pen/KdXwxR
this is the error :
here my html code :
<div class="chat-area scrollbar-macosx scroll-wrapper">
<div class="chat-area-content scrollbar-macosx">
<ul class="container">
<!-- Label Time Chat -->
<div class="text-center mt-3">
<span class="label-time">30 Apr</span>
</div>
<!-- Merchant chat -->
<div class="d-flex justify-content-start mt-3">
<div class="chat-content-image">
<div class="upload-image">
<div class="time-image">
<span class="time-item">14:10</span>
</div>
</div>
</div>
</div>
<!-- Customer chat -->
<div class="d-flex justify-content-start mt-3">
<div class="chat-context">
<div class="chat-text">
<p></p>
</div>
<div class="chat-time">
<p>14:15</p>
</div>
</div>
</div>
<!-- Customer Chat -->
<div class="d-flex justify-content-end mt-3 mb-4">
<div class="chat-context">
<div class="chat-text">
<p></p>
</div>
<div class="chat-time">
<p>15:00</p>
</div>
</div>
</div>
</ul>
</div>
<form class="keyboard-chat">
<div class="chat-input">
<div class="attach-button mr-3 mb-3">
<button type="button" class="circle-button">
<i class="fa fa-plus"></i>
</button>
</div>
<div class="chat-input-textarea" style="padding-left: 0px;">
<div>
<textarea id="message-to-send" name="message-to-send" placeholder="Type here..." rows="3" class="keyboards f-size-12" style="max-height: 130px;"></textarea>
</div>
</div>
<div class="btn-submit-message mb-3"></div>
</div>
</form>
</div>
<script id="message-template" type="text/x-handlebars-template">
<div class="d-flex justify-content-end mt-3">
<div class="chat-context">
<div class="chat-text">
<p>{{messageOutput}}</p>
</div>
<div class="chat-time">
<p>{{time}}</p>
</div>
</div>
</div>
</script>
And here my js :
(function(){
var chat = {
messageToSend: '',
messageResponses: [
'Why did the web developer leave the restaurant? Because of the table layout.',
'How do you comfort a JavaScript bug? You console it.',
'An SQL query enters a bar, approaches two tables and asks: "May I join you?"',
'What is the most used language in programming? Profanity.',
'What is the object-oriented way to become wealthy? Inheritance.',
'An SEO expert walks into a bar, bars, pub, tavern, public house, Irish pub, drinks, beer, alcohol'
],
init: function() {
this.cacheDOM();
this.bindEvents();
this.render();
},
cacheDOM: function() {
this.$chatHistory = $('.chat-area-content');
this.$button = $('.btn-submit-message');
this.$textarea = $('#message-to-send');
this.$chatHistoryList = this.$chatHistory.find('ul');
},
bindEvents: function() {
this.$button.on('click', this.addMessage.bind(this));
this.$textarea.on('keyup', this.addMessageEnter.bind(this));
},
render: function() {
this.scrollToBottom();
if (this.messageToSend.trim() !== '') {
var template = Handlebars.compile( $("#message-template").html());
var context = {
messageOutput: this.messageToSend,
time: this.getCurrentTime()
};
this.$chatHistoryList.append(template(context));
this.scrollToBottom();
this.$textarea.val('');
// responses
var templateResponse = Handlebars.compile( $("#message-response-template").html());
var contextResponse = {
response: this.getRandomItem(this.messageResponses),
time: this.getCurrentTime()
};
setTimeout(function() {
this.$chatHistoryList.append(templateResponse(contextResponse));
this.scrollToBottom();
}.bind(this), 1500);
}
},
addMessage: function() {
this.messageToSend = this.$textarea.val()
this.render();
},
addMessageEnter: function(event) {
// enter was pressed
if (event.keyCode === 13) {
this.addMessage();
}
},
scrollToBottom: function() {
this.$chatHistory.scrollTop(this.$chatHistory[0].scrollHeight);
},
getCurrentTime: function() {
return new Date().toLocaleTimeString().
replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, "$1$3");
},
getRandomItem: function(arr) {
return arr[Math.floor(Math.random()*arr.length)];
}
};
chat.init();
})();
Code of .js same like in the tutorial, but i only change the name class i used.
My Expectation is when i enter / click button send, the conversation is submited to the chat area.
This code requires Handlebars JS since you call Handlebars. You can it install it by follwing the installation steps on the website.

AngularJs, How to edit $scope values in other div using the same controller with factory

I would like to use two different divs one contains a form and other contains repeat for the $scope values. Those two divs needs to use the same controller. However I am not able to share data in between divs in a desired way. Although I use factory, it only helps for me to add data to scope. I also want to edit the scope values inside the form which has another instance of the same controller.
You can find what I did in this link.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
<body>
<script>
var app = angular.module("myShoppingList", []);
app.factory('fact',function(){
products = ["milk","chese"];
tempItem = '';
tempIndex = undefined;
return {
getProducts : function() {
return products;
},
getProductByIndex : function(x){
return products[x];
},
saveProduct : function(x,item)
{
if(x==undefined)
{
products.push(item);
}
else
{
products[x] = item;
}
tempItem = '';
tempIndex = undefined;
},
editProduct : function(x)
{
tempItem = products[x];
tempIndex = x;
},
removeProduct : function(x)
{
products.splice(x, 1);
},
getTempItem : function()
{
return tempItem;
},
getTempIndex : function()
{
return tempIndex;
},
}
});
app.controller("myCtrl", function($scope, fact) {
$scope.products = fact.getProducts();
$scope.tempIndex = fact.getTempIndex();
$scope.tempItem = fact.getTempItem();
$scope.saveItem = function () {
fact.saveProduct($scope.tempIndex,$scope.tempItem);
}
$scope.editItem = function (x) {
fact.editProduct(x);
}
$scope.removeItem = function (x) {
fact.removeProduct(x);
}
});
</script>
<div ng-app="myShoppingList" ng-cloak class="w3-card-2 w3-margin" style="max-width:400px;">
<header class="w3-container w3-light-grey w3-padding-16">
<h3>My Shopping List</h3>
</header>
<div ng-controller="myCtrl">
<ul class="w3-ul">
<li ng-repeat="x in products" class="w3-padding-16">{{$index}} {{x}}
<span ng-click="editItem($index)" style="cursor:pointer;" class="w3-right w3-margin-right">||</span>
<span ng-click="removeItem($index)" style="cursor:pointer;" class="w3-right w3-margin-right">×</span>
</ul>
</div>
<div ng-controller="myCtrl" class="w3-container w3-light-grey w3-padding-16">
<form ng-submit="saveItem()">
<div class="w3-row w3-margin-top">
<div class="w3-col s10">
<input placeholder="Add shopping items here" ng-model="tempItem" class="w3-input w3-border w3-padding">
<input type="hidden" ng-model="tempIndex">
</div>
<div class="w3-col s2">
<button type="submit" class="w3-btn w3-padding w3-green">Save</button>
</div>
</div>
</form>
</div>
</div>
</body>
</html>
ISSUES
You have initialized controller twice.
You can do edit item inside controller itself.
After saving $scope values should be cleared along with clearing values in factory.
CONTROLLER and HTML
var app = angular.module("myShoppingList", []);
app.factory('fact',function(){
products = ["milk","chese"];
tempItem = '';
tempIndex = undefined;
return {
getProducts : function() {
return products;
},
getProductByIndex : function(x){
return products[x];
},
saveProduct : function(x,item)
{
if(!x)
{
products.push(item);
}
else
{
products[x] = item;
}
tempItem = '';
tempIndex = '';
},
editProduct : function(x)
{
tempItem = products[x];
tempIndex = x;
},
removeProduct : function(x)
{
products.splice(x, 1);
},
getTempItem : function()
{
return tempItem;
},
getTempIndex : function()
{
return tempIndex;
},
}
});
app.controller("myCtrl", function($scope, fact) {
$scope.products = fact.getProducts();
$scope.tempIndex = fact.getTempIndex();
$scope.tempItem = fact.getTempItem();
$scope.saveItem = function () {
fact.saveProduct($scope.tempIndex,$scope.tempItem);
$scope.tempItem = '';
$scope.tempIndex = '';
}
$scope.editItem = function (x) {
$scope.tempItem = fact.getProducts()[x];
$scope.tempIndex = x;
}
$scope.removeItem = function (x) {
fact.getProducts().splice(x, 1);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
<div ng-app="myShoppingList" ng-controller="myCtrl" ng-cloak class="w3-card-2 w3-margin" style="max-width:400px;">
<header class="w3-container w3-light-grey w3-padding-16">
<h3>My Shopping List</h3>
</header>
<div>
<ul class="w3-ul">
<li ng-repeat="x in products" class="w3-padding-16">{{$index}} {{x}}
<span ng-click="editItem($index)" style="cursor:pointer;" class="w3-right w3-margin-right">||</span>
<span ng-click="removeItem($index)" style="cursor:pointer;" class="w3-right w3-margin-right">×</span>
</ul>
</div>
<div class="w3-container w3-light-grey w3-padding-16">
<form ng-submit="saveItem()">
<div class="w3-row w3-margin-top">
<div class="w3-col s10">
<input placeholder="Add shopping items here" ng-model="tempItem" class="w3-input w3-border w3-padding">
<input type="hidden" ng-model="tempIndex">
</div>
<div class="w3-col s2">
<button type="submit" class="w3-btn w3-padding w3-green">Save</button>
</div>
</div>
</form>
</div>
</div>

how to generate list dynamically in angular.js

can you please tell me how to create list dynamically in angulat.js..Actullly I am able to make list when user press add button and fill the field .
In other words ,Please check this fiddle whenever you fill the fields it generate a row.And you can get Id when you click the row .Fiddle http://jsfiddle.net/wc4Jm/6/
Now I am trying to do this using bootstrap model .in other words on button click first I show a pop up screen then there is "add" button .on click that it generate the row.but I am getting "undefined".My I insert the model div inside the controller ? here is
http://jsbin.com/vubojoxo/4/
Why I am getting this error ?
XMLHttpRequest cannot load file:///C:/Users/asd/Desktop/angular/angularproject/dialog.html. Received an invalid response. Origin 'null' is therefore not allowed access.
I am getting this error when I used plunker..and run in my desktop ..
I make this html ?
<!doctype html>
<html ng-app="plunker">
<head>
<script src="angular.js"></script>
<script src="ui-bootstrap-tpls-0.2.0.js"></script>
<link href="bootstrap-combined.min.css" rel="stylesheet">
<script src="index.js"></script>
</head>
<body>
<div ng-controller="DialogDemoCtrl">
<a class="btn" data-toggle="modal" href="" ng-click="openPopupScreen()">Add Contend</a>
</div>
</body>
</html>
....
Dialog.html
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h1>Add Element</h1>
</div>
<div class="modal-body">
<form >
<label>Name:</label><input type="text" class="span3" ng-model="activeItem.name"></br>
<label>Content Name:</label><input type="password" class="span3" ng-model="activeItem.content"></br>
<button type="submit" class="btn btn-success" ng-click="addItem()">Add In List</button>
<button type="reset" class="btn ">Clear</button>
</form>
</div>
<div class="modal-footer">
<a class="btn" data-dismiss="modal" aria-hidden="true">close</a>
</div>
js code:
var myApp = angular.module('plunker', ['ui.bootstrap']);
myApp.controller('DialogDemoCtrl', function($scope,$dialog) {
$scope.items = [];
$scope.activeItem = {
id:'',
name: '',
content: ''
};
$scope.addItem = function () {
$scope.activeItem.id = $scope.items.length + 1;
$scope.items.push($scope.activeItem);
$scope.activeItem = {}; /* reset active item*/
};
$scope.getId = function (item) {
alert('ID: '+item.id);
};
$scope.openPopupScreen = function () {
alert('Check Open pop up screen');
$dialog.dialog({}).open('dialog.html');
};
});
Check this Plunker
In this example i used angular-ui library which wraps bootstrap's modal to angular
based on this StackOverflow Answer
ModalDemoCtrl
$scope.items = [];
$scope.getId = function(item) {
alert('ID: ' + item.id);
};
// This opens a Bootstrap modal
$scope.open = function() {
var modalInstance = $modal.open({
template: $scope.modal_html_template,
controller: ModalInstanceCtrl
});
modalInstance.result.then(function(newItem) {
// On modal success
newItem.id = $scope.items.length + 1;
$scope.items.push(newItem);
}, function() {
// On modal cancelation
});
}
ModalInstanceCtrl
$scope.name = '';
$scope.content = '';
$scope.ok = function() {
var response = {
'name': $scope.name,
'content': $scope.content
};
$modalInstance.close(response);
};
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
HTML
<body>
<div ng-controller="ModalDemoCtrl">
<div inner-html-bind="" inner-html="modal_html_template" class="hidden">
<div class="modal-header">
<h3>I'm a modal!</h3>
</div>
<div class="modal-body">
<div class="form-group">
<label>Name</label>
<!-- using $parent because ui-bootstrap nested 2 controllers. this is a workaround -->
<input type="text" class="form-control" ng-model="$parent.name" placeholder="Enter Name">
</div>
<div class="form-group">
<label>Content</label>
<!-- using $parent because ui-bootstrap nested 2 controllers. this is a workaround -->
<input type="text" class="form-control" ng-model="$parent.content" placeholder="Enter Content">
</div>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="ok()">OK</button>
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
</div>
<div class="container">
<h2>Modal Example https://stackoverflow.com/questions/24988561</h2>
<button class="btn" ng-click="open()">Open Modal</button>
<div>
<ul>
<li ng-repeat="item in items">
<a ng-click="getId(item)">{{ item.id }} | {{ item.name + ' ' + item.content }}</a>
</li>
</ul>
</div>
</div>
</div>
</body>

AngularJS : call a Controller method with ng-click [duplicate]

I have a simple loop with ng-repeat like this:
<li ng-repeat='task in tasks'>
<p> {{task.name}}
<button ng-click="removeTask({{task.id}})">remove</button>
</li>
There is a function in the controller $scope.removeTask(taskID).
As far as I know Angular will first render the view and replace interpolated {{task.id}} with a number, and then, on click event, will evaluate ng-click string.
In this case ng-click gets totally what is expected, ie: ng-click="removeTask(5)". However... it's not doing anything.
Of course I can write a code to get task.id from the $tasks array or even the DOM, but this does not seem like the Angular way.
So, how can one add dynamic content to ng-click directive inside a ng-repeat loop?
Instead of
<button ng-click="removeTask({{task.id}})">remove</button>
do this:
<button ng-click="removeTask(task.id)">remove</button>
Please see this fiddle:
http://jsfiddle.net/JSWorld/Hp4W7/34/
One thing that really hung me up, was when I inspected this html in the browser, instead of seeing it expanded to something like:
<button ng-click="removeTask(1234)">remove</button>
I saw:
<button ng-click="removeTask(task.id)">remove</button>
However, the latter works!
This is because you are in the "Angular World", when inside ng-click="" Angular all ready knows about task.id as you are inside it's model. There is no need to use Data binding, as in {{}}.
Further, if you wanted to pass the task object itself, you can like:
<button ng-click="removeTask(task)">remove</button>
Also worth noting, for people who find this in their searches, is this...
<div ng-repeat="button in buttons" class="bb-button" ng-click="goTo(button.path)">
<div class="bb-button-label">{{ button.label }}</div>
<div class="bb-button-description">{{ button.description }}</div>
</div>
Note the value of ng-click. The parameter passed to goTo() is a string from a property of the binding object (the button), but it is not wrapped in quotes. Looks like AngularJS handles that for us. I got hung up on that for a few minutes.
this works. thanks. I am injecting custom html and compile it using angular in the controller.
var tableContent= '<div>Search: <input ng-model="searchText"></div>'
+'<div class="table-heading">'
+ '<div class="table-col">Customer ID</div>'
+ ' <div class="table-col" ng-click="vm.openDialog(c.CustomerId)">{{c.CustomerId}}</div>';
$timeout(function () {
var linkingFunction = $compile(tableContent);
var elem = linkingFunction($scope);
// You can then use the DOM element like normal.
jQuery(tablePanel).append(elem);
console.log("timeout");
},100);
Above answers are excellent. You can look at the following full code example so that you could exactly know how to use
var app = angular.module('hyperCrudApp', []);
app.controller('usersCtrl', function($scope, $http) {
$http.get("https://jsonplaceholder.typicode.com/users").then(function (response) {
console.log(response.data)
$scope.users = response.data;
$scope.setKey = function (userId){
alert(userId)
if(localStorage){
localStorage.setItem("userId", userId)
} else {
alert("No support of localStorage")
return
}
}//function closed
});
});
#header{
color: green;
font-weight: bold;
}
<!DOCTYPE html>
<html>
<head>
<title>HyperCrud</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</head>
<body>
<!-- NAVBAR STARTS -->
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">HyperCrud</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="active">Home</li>
<li>About</li>
<li>Contact</li>
<li class="dropdown">
Apps<span class="caret"></span>
<ul class="dropdown-menu">
<li>qAlarm »</li>
<li>YtEdit »</li>
<li>GWeather »</li>
<li role="separator" class="divider"></li>
<li>WadStore »</li>
<li>chatsAll</li>
</ul>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li>Login</li>
<li>Register</li>
<li>Services<span class="sr-only">(current)</span></li>
</ul>
</div>
</div>
</nav>
<!--NAVBAR ENDS-->
<br>
<br>
<div ng-app="hyperCrudApp" ng-controller="usersCtrl" class="container">
<div class="row">
<div class="col-sm-12 col-md-12">
<center>
<h1 id="header"> Users </h1>
</center>
</div>
</div>
<div class="row" >
<!--ITERATING USERS LIST-->
<div class="col-sm-6 col-md-4" ng-repeat="user in users">
<div class="thumbnail">
<center>
<img src="https://cdn2.iconfinder.com/data/icons/users-2/512/User_1-512.png" alt="Image - {{user.name}}" class="img-responsive img-circle" style="width: 100px">
<hr>
</center>
<div class="caption">
<center>
<h3>{{user.name}}</h3>
<p>{{user.email}}</p>
<p>+91 {{user.phone}}</p>
<p>{{user.address.city}}</p>
</center>
</div>
<div class="caption">
DELETE
UPDATE
</div>
</div>
</div>
<div class="col-sm-6 col-md-4">
<div class="thumbnail">
<a href="/regiser/">
<img src="http://img.bhs4.com/b7/b/b7b76402439268b532e3429b3f1d1db0b28651d5_large.jpg" alt="Register Image" class="img-responsive img-circle" style="width: 100%">
</a>
</div>
</div>
</div>
<!--ROW ENDS-->
</div>
</body>
</html>
HTML:
<div ng-repeat="scannedDevice in ScanResult">
<!--GridStarts-->
<div >
<img ng-src={{'./assets/img/PlaceHolder/Test.png'}}
<!--Pass Param-->
ng-click="connectDevice(scannedDevice.id)"
altSrc="{{'./assets/img/PlaceHolder/user_place_holder.png'}}"
onerror="this.src = $(this).attr('altSrc')">
</div>
</div>
Java Script:
//Global Variables
var ANGULAR_APP = angular.module('TestApp',[]);
ANGULAR_APP .controller('TestCtrl',['$scope', function($scope) {
//Variables
$scope.ScanResult = [];
//Pass Parameter
$scope.connectDevice = function(deviceID) {
alert("Connecting : "+deviceID );
};
}]);
Here is the ng repeat with ng click function and to append with slider
<script>
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope) {
$scope.employees = [
{ 'id': '001', 'name': 'Alpha', 'joinDate': '05/17/2015', 'age': 37 },
{ 'id': '002', 'name': 'Bravo', 'joinDate': '03/25/2016', 'age': 27 },
{ 'id': '003', 'name': 'Charlie', 'joinDate': '09/11/2015', 'age': 29 },
{ 'id': '004', 'name': 'Delta', 'joinDate': '09/11/2015', 'age': 19 },
{ 'id': '005', 'name': 'Echo', 'joinDate': '03/09/2014', 'age': 32 }
]
//This will hide the DIV by default.
$scope.IsVisible = false;
$scope.ShowHide = function () {
//If DIV is visible it will be hidden and vice versa.
$scope.IsVisible = $scope.IsVisible ? false : true;
}
});
</script>
</head>
<body>
<div class="container" ng-app="MyApp" ng-controller="MyController">
<input type="checkbox" value="checkbox1" ng-click="ShowHide()" /> checkbox1
<div id="mixedSlider">
<div class="MS-content">
<div class="item" ng-repeat="emps in employees" ng-show = "IsVisible">
<div class="subitem">
<p>{{emps.id}}</p>
<p>{{emps.name}}</p>
<p>{{emps.age}}</p>
</div>
</div>
</div>
<div class="MS-controls">
<button class="MS-left"><i class="fa fa-angle-left" aria-hidden="true"></i></button>
<button class="MS-right"><i class="fa fa-angle-right" aria-hidden="true"></i></button>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="js/multislider.js"></script>
<script>
$('#mixedSlider').multislider({
duration: 750,
interval: false
});
</script>

emberjs arraycontroller issue

I am new to Ember and am having an issue. I would like the user to be able to select a number of workstations, and when they hit the next button, I would like the controller to create a number of objects equal to the number the user selected. Once they are taken to the next screen I want to view to append a number of divs with the questions equal to the number the user selected.
I have this for the app.js:
//Initialize the application
App = Ember.Application.create({
rootElement: '#main'
});
//Initialize the data model
App.CustomerController = Ember.Object.extend({
first: null,
last: null,
email: null,
phone: null,
clinic: null,
number: null
});
App.Workstation = Ember.Object.extend({
id: null,
title: null,
newOrExisting: null,
cabling: null
});
App.workstationController = Ember.ArrayController.create({
content: [],
num: null,
init: function() {
this.set('content',[]);
var num = this.get('num');
var tempId = Date.now();
var ws = App.Workstation.create({
id: tempId
});
this.pushObject(ws);
}
});
App.selectNoComputers = ["1", "2", "3", "4", "5"];
App.workstationSelect = ["Counter 1", "Counter 2", "Counter 3", "Counter 4", "Office 1", "Office 2", "Office 3"];
App.yesNo = ["New", "Existing"];
App.Router.map(function(match) {
match("/").to("captcha");
match("/customer").to("customer");
match("/wsnum").to("computers");
match("/overview").to("overview");
});
App.CaptchaRoute = Ember.Route.extend({
renderTemplate: function() {
this.render('captcha');
}
});
App.CustomerRoute = Ember.Route.extend();
App.ComputersRoute = Ember.Route.extend();
App.OverviewRoute = Ember.Route.extend({
});
App.initialize();
And this for my html:
<script type="text/x-handlebars" data-template-name="overview">
<div class="navbar">
<div class="navbar-inner">
<div class="progress-bar-label-div">
Progress:
</div>
<div class="progress-bar-div">
<div class="progress progress-striped">
<div class="bar" style="width:60%;"></div>
</div>
</div>
<div class="btn-group pull-right">
{{#linkTo "computers" class="btn"}}
Prev
{{/linkTo}}
</div>
</div>
</div>
<div class="row-a top">
<div class="pull-left" >
<h3>Workstation Overview</h3>
</div>
<div class="pull-right">
</div>
</div>
{{#each App.workstationController}}
<div class="workstation-b">
<div class="row-b">
<div class="pull-left workstation-title" >
<h4>{{id}}</h4>
</div>
<div class="pull-right form-inputs input-text">
<a class="btn btn-primary" >
Start
</a>
</div>
</div>
<div class="row-b">
<div class="pull-left questions">
What station will this be?
</div>
<div class="pull-right form-inputs input-text">
{{view Ember.Select prompt="Please Select" contentBinding="App.workstationSelect"}}
</div>
</div>
<div class="row-b">
<div class="pull-left questions">
Is this computer a new purchase or replacing and existing workstation?
</div>
<div class="pull-right form-inputs input-text">
{{view Ember.Select prompt="Please Select" contentBinding="App.yesNo"}}
</div>
</div>
</div>
{{/each}}
</script>
I'm sure I'm missing something pretty easy, but any help is appreciated.
I put together a fiddle to illustrate my problem.
Working fiddle: http://jsfiddle.net/mgrassotti/xtNXw/3/
Relevant changes: Added an observer to listen for changes to the num property. When it changes, the content array is reset and then an appropriate number of blank workstation objects are created.
App.workstationController = Ember.ArrayController.create({
content: [],
num: null,
init: function() {
this.set('content',[]);
},
addBlankWorkstation: function() {
var tempId = Date.now();
var ws = App.Workstation.create({
id: tempId
});
this.pushObject(ws);
}
});
App.workstationController.addObserver( 'num', function() {
var num = this.get('num');
this.set('content',[]);
for (var i=0;i<num;i++) {
this.addBlankWorkstation();
}
});
I hesitated to say working fiddle above since there are many things that might be worth refactoring. You'll find most of the complexity could be reduced by following ember naming conventions. Suggest looking at latest guides for more detail.

Categories

Resources