AngularJS material floating label on autocomplete and chips - javascript

I'm working with the AngularJS material design library, and I'm looking to make a input box, with a floating label, with autocomplete, and chips to denote the options the users have selected. The best I've gotten is:
https://codepen.io/anon/pen/eeqBKK
HTML:
<div ng-controller="CustomInputDemoCtrl as ctrl" layout="column" ng-cloak="" class="chipsdemoCustomInputs" ng-app="MyApp">
<md-content class="md-padding" layout="column">
<md-chips ng-model="ctrl.selectedVegetables" md-autocomplete-snap="" md-transform-chip="ctrl.transformChip($chip)" md-require-match="ctrl.autocompleteDemoRequireMatch">
<md-autocomplete md-selected-item="ctrl.selectedItem" md-search-text="ctrl.searchText" md-items="item in ctrl.querySearch(ctrl.searchText)" md-item-text="item.name" placeholder="Choose your favourite colors">
<span md-highlight-text="ctrl.searchText">{{item.name}}</span>
</md-autocomplete>
<md-chip-template>
<span>
<strong>{{$chip.name}}</strong>
<em>({{$chip.type}})</em>
</span>
</md-chip-template>
</md-chips>
</md-content>
</div>
JavaScript:
(function () {
'use strict';
angular
.module('MyApp',['ngMaterial', 'ngMessages', 'material.svgAssetsCache'])
.controller('CustomInputDemoCtrl', DemoCtrl);
function DemoCtrl ($timeout, $q) {
var self = this;
self.readonly = false;
self.selectedItem = null;
self.searchText = null;
self.querySearch = querySearch;
self.colors = loadColors();
self.selectedColors = [];
self.numberChips = [];
self.numberChips2 = [];
self.numberBuffer = '';
self.autocompleteDemoRequireMatch = true;
self.transformChip = transformChip;
function transformChip(chip) {
if (angular.isObject(chip)) {
return chip;
}
return { name: chip, type: 'new' }
}
function querySearch (query) {
var results = query ? self.colors.filter(createFilterFor(query)) : [];
return results;
}
function createFilterFor(query) {
var lowercaseQuery = angular.lowercase(query);
return function filterFn(colors) {
return (colors._lowername.indexOf(lowercaseQuery) === 0) ||
(colors._lowertype.indexOf(lowercaseQuery) === 0);
};
}
function loadColors() {
var colorOptions = [{'name': 'Red','type': 'Color'},{'name': 'Orange','type': 'Color'},{'name': 'Yellow','type': 'Color'},{'name': 'Green','type': 'Color'},{'name': 'Blue','type': 'Color'},{'name': 'Purple','type': 'Color'}
];
return colorOptions.map(function(col) {
col._lowername = col.name.toLowerCase();
col._lowertype = col.type.toLowerCase();
return col;
});
}
}
})();
Which, has the input box, the autocomplete, the chips to denote the options but not the floating label on the text area. Is it possible to have the floating label in this setup?

Related

How to apply multiple filters with pagination in Angular JS?

I am trying to apply multiple filters with pagination in Angular JS i am able to paginate the results with one filter but whenever there is multiple filters i am unable do it OR is performing among two filters instead of AND please help me to achieve this any help will be greatly appreciated. here is my code.
Here is my index.html
<html xmlns:ng="http://angularjs.org" ng-app lang="en">
<head>
<meta charset="utf-8">
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.1.1/css/bootstrap.no-icons.min.css" rel="stylesheet">
<link href="http://netdna.bootstrapcdn.com/font-awesome/2.0/css/font-awesome.css" rel="stylesheet">
<script src="http://code.angularjs.org/1.1.0/angular.min.js"></script>
</head>
<body>
</div>
<div ng-controller="ctrlRead">
<div class="input-append">
<input type="text" ng-model="name" ng-change="nameSearch()" class="input-large search-query" placeholder="Search Name">
<input type="text" ng-model="country" ng-change="countrySearch()" class="input-large search-query" placeholder="Search Name">
<span class="add-on"><i class="icon-search"></i></span>
</div>
<div class="pagination pull-right">
<ul>
<li ng-class="{disabled: currentPage == 0}">
<a href ng-click="prevPage()">« Prev</a>
</li>
<li ng-repeat="n in range(pagedItems.length)"
ng-class="{active: n == currentPage}"
ng-click="setPage()">
<a href ng-bind="n + 1">1</a>
</li>
<li ng-class="{disabled: currentPage == pagedItems.length - 1}">
<a href ng-click="nextPage()">Next »</a>
</li>
</ul>
</div>
</div>
</body>
</html>
And here is my script.
function ctrlRead($scope, $filter) {
// init
$scope.sortingOrder = sortingOrder;
$scope.reverse = false;
$scope.filteredItems = [];
$scope.groupedItems = [];
$scope.itemsPerPage = 5;
$scope.pagedItems = [];
$scope.currentPage = 0;
$scope.items = [
{"id":"1","name":"John","country":"usa"},
{"id":"2","name":"Peter",,"country":"London"}];
// init the filtered items
$scope.nameSearch = function () {
$scope.filteredItems = $filter('filter')($scope.items, function (item) {
if(item.name.includes($scope.name)){
return true;
}
});
$scope.countrySearch = function () {
$scope.filteredItems = $filter('filter')($scope.items, function (item) {
if(item.country.includes($scope.country)){
return true;
}
});
$scope.currentPage = 0;
// now group by pages
$scope.groupToPages();
};
// calculate page in place
$scope.groupToPages = function () {
$scope.pagedItems = [];
for (var i = 0; i < $scope.filteredItems.length; i++) {
if (i % $scope.itemsPerPage === 0) {
$scope.pagedItems[Math.floor(i / $scope.itemsPerPage)] = [ $scope.filteredItems[i] ];
} else {
$scope.pagedItems[Math.floor(i / $scope.itemsPerPage)].push($scope.filteredItems[i]);
}
}
};
$scope.range = function (start, end) {
var ret = [];
if (!end) {
end = start;
start = 0;
}
for (var i = start; i < end; i++) {
ret.push(i);
}
return ret;
};
$scope.prevPage = function () {
if ($scope.currentPage > 0) {
$scope.currentPage--;
}
};
$scope.nextPage = function () {
if ($scope.currentPage < $scope.pagedItems.length - 1) {
$scope.currentPage++;
}
};
$scope.setPage = function () {
$scope.currentPage = this.n;
};
// functions have been describe process the data for display
$scope.search();
};
ctrlRead.$inject = ['$scope', '$filter'];
Hope this will help you, I am using standard filter and 2 other drop downs through which I am doing filter in table.
HTML Code
<div>
<label>Associated Products:</label>
<div class="row">
<div class="col-md-6">
<div class="col-md-4 custom-select">
<div class="custom-select-text">{{selected}}</div>
<select class="form-control select-area c-corporate-contact-us-from-select-country country-lang-select" data-widget="custom-select"
(change)="onSelectProductLine($event)" [(ngModel)]="selected">
<option value="0">Select a product line</option>
<option *ngFor="let ProductLine of productLines" value={{ProductLine.categoryId}}>
{{ProductLine.title}}
</option>
</select>
</div>
</div>
<div class="col-md-6">
<div class="col-md-4 custom-select" *ngIf="edited">
<div class="custom-select-text">{{selectedProduct}}</div>
<select class="form-control select-area c-corporate-contact-us-from-select-country country-lang-select" data-widget="custom-select"
(change)="onSelectProduct($event)" [(ngModel)]="selectedProduct">
<option value="0">Select a product</option>
<option *ngFor="let Product of products" value={{Product.categoryId}}>
{{Product.title}}
</option>
</select>
</div>
</div>
</div>
</div>
<div class="example-header">
<mat-form-field>
<input matInput (page)="changePage($event)" (keyup)="applyFilter($event.target.value)" placeholder="Search Products based on Product Numbers or Description or Associate Products">
</mat-form-field>
</div>
JS Code
onSelectProductLine(args) {
if (args.target.value != 0)
this.edited = true;
else
this.edited = false;
this.dataservice.getProduct(args.target.value).subscribe(res => this.products = res);
this.selected = args.target.options[args.target.selectedIndex].text;
this.applyFilterTopLevelProduct(this.selected);
}
onSelectProduct(args) {
this.selectedProduct = args.target.options[args.target.selectedIndex].text;
this.applyFilterSecondLevelProduct(this.selectedProduct);
}
applyFilter(filterValue: string) {
debugger;
filterValue = filterValue.trim(); // Remove whitespace
filterValue = filterValue.toLowerCase(); // Datasource defaults to lowercase matches
this.dataSource.filterPredicate =
(data: IFUsApi, filter: string) => {
let searchStr = (data.productNumbers + data.title + data.associatedProducts).toLowerCase();
return searchStr.indexOf(filter.toLowerCase()) != -1;
}
this.dataSource.filter = filterValue;
}
applyFilterTopLevelProduct(filterValue: string) {
debugger;
if (filterValue == "Select a product line")
filterValue = "";
filterValue = filterValue.trim(); // Remove whitespace
filterValue = filterValue.toLowerCase(); // Datasource defaults to lowercase matches
this.dataSource.filterPredicate =
(data: IFUsApi, filter: string) => {
let searchStr = (data.toplevelProduct).toLowerCase();
return searchStr.indexOf(filter.toLowerCase()) != -1;
}
this.dataSource.filter = filterValue;
}
applyFilterSecondLevelProduct(filterValue: string) {
if (filterValue == "Select a product") {
filterValue = this.selected;
this.dataSource.filterPredicate =
(data: IFUsApi, filter: string) => {
let searchStr = (data.toplevelProduct).toLowerCase();
return searchStr.indexOf(filter.toLowerCase()) != -1;
}
this.dataSource.filter = filterValue;
}
else {
filterValue = filterValue.trim(); // Remove whitespace
filterValue = filterValue.toLowerCase(); // Datasource defaults to lowercase matches
this.dataSource.filterPredicate =
(data: IFUsApi, filter: string) => {
let searchStr = (data.associatedProducts).toLowerCase();
return searchStr.indexOf(filter.toLowerCase()) != -1;
}
this.dataSource.filter = filterValue;
}
}

input value returns NaN on ng-click

I am writing a program that takes in input value for two numbers and provides a random value from the range specified. I have fixed controllers to shuffle min and max value and it works once i place numbers but if i add the ng-model value, it returns "NaN". Here is the html
<div class="col-sm-4" ng-controller="ValueController">
<div class="row">
<div class="col-sm-6"><input type="number" ng-model="value.one">
</div>
<div class="col-sm-6"><input ng-model="value.two"></div>
</div>
</div>
<div class="col-sm-4">
<a ng-href="results.html" ng-controller="ShuffleController"
ng-click="shuffle(100100, 110000)">
<img src="img/before.png" style="width: 500px; height: auto;"></a>
</ul>
</div>
Here is part of the app.js:
// Angular App Initialization
var app = angular.module('Shuffle', ['ngRoute']);
// Declaring Globals
app.run(function($rootScope) {
$rootScope.shuffled = [];
$rootScope.shuffleValues = {};
$rootScope.getRand = function(min, max) {
var number = Math.floor(Math.random() * (max - min)) + min;
var leadingZeroes = 6 - number.toString().length;
$rootScope.shuffled.push([[min, max], number.toString().length < 6 ? ('0'.repeat(leadingZeroes) + number) : number]);
window.localStorage.setItem('shuffled', JSON.stringify($rootScope.shuffled));
}
});
// Shuffle Controller
app.controller('ShuffleController', function($scope, $rootScope, $window) {
console.log('Welcome to TheShuffler!');
var results = window.localStorage.getItem('shuffled');
results = JSON.parse(results);
$scope.shuffle = function(min, max) {
console.log("You shuffled!");
console.log(results);
$rootScope.getRand(min, max);
}
});
// Results Controller
app.controller('ResultsController', function($scope) {
var results = window.localStorage.getItem('shuffled');
$scope.shuffleResults = JSON.parse(results);
$scope.quantity = 3;
console.log($scope.shuffleResults);
});
// Reshuffling Controller
app.controller('ReshuffleController', function($scope, $rootScope, $route, $window, $location) {
$scope.reshuffle = function(){
$window.location.reload();
console.log('You reshuffled!');
var results = window.localStorage.getItem('shuffled');
results = $scope.shuffleResults = JSON.parse(results);
for (var i = 0; i < results.length; i++) {
var min = results[i][0][0]
var max = results[i][0][1]
$rootScope.getRand(min, max)
}
}
});
// Shuffle Entries Verification Controller
app.controller('ShuffleEntriesVerificationController', function($scope, $window) {
console.log('EntriesHere!');
$scope.entryCheck = function(){
var results = window.localStorage.getItem('shuffled');
results = JSON.parse(results);
console.log("You checked!");
console.log(results);
var verficationMessage = "Maximum Entries Exceeded. Please Click Shuffle";
if (results.length > 2) {
$window.alert(verficationMessage);
$window.location.reload();
}
}
});
app.controller('ValueController', ['$scope', function($scope) {
$scope.value = {
one: 000100,
two: 005100
};
}]);
it('should check ng-bind', function() {
var nameInput = element(by.model('value'));
expect(element(by.binding('value')).getText()).toBe('Whirled');
nameInput.clear();
nameInput.sendKeys('world');
expect(element(by.binding('value')).getText()).toBe('world');
});
I get NaN when i do this:
<a ng-href="results.html" ng-controller="ShuffleController"
ng-click="shuffle(value.one, value.two)">
<img src="img/before.png" style="width: 500px; height: auto;"></a>
What is the problem?
You have a wrong controller:
ng-controller="ShuffleController"
while in your app you have this controller:
app.controller('ValueController',...
...
}]);
You don't have to pass the model as parameter values will be automatically bound and available in your shuffle function.
In case of your NaN error create a snippet to get a better perspective of your problem

My ng-click is not firing

I'm new to Angular, so please bear with me.
I have an app I'm building where you can hit an "X" or a heart to dislike/like something. I'm using a swipe library called ng-swippy.
I'm trying to use ng-click="clickLike()"for the "Like" button and ng-click="clickDislike()"but neither are firing. I can't figure out what's going on.
Here's the URL:
http://430designs.com/xperience/black-label-app/deck.php
deck.php code
<ng-swippy collection='deck' item-click='myCustomFunction'
data='showinfo' collection-empty='swipeend' swipe-left='swipeLeft'
swipe-right='swipeRight' cards-number='4' label-ok='Cool'
label-negative='Bad'>
</ng-swippy>
The template is called from card-tpl.html:
<div class="ng-swippy noselect">
<div person="person" swipe-directive="swipe-directive" ng-repeat="person in peopleToShow" class="content-wrapper swipable-card">
<div class="card">
<div style="background: url({{person.thumbnail}}) no-repeat 50% 15%" class="photo-item"></div>
<div class="know-label">{{labelOk ? labelOk : "YES"}}</div>
<div class="dontknow-label">{{labelNegative ? labelNegative : "NO"}}</div>
</div>
<div class="progress-stats" ng-if="data">
<div class="card-shown">
<div class="card-shown-text">{{person.collection}}</div>
<div class="card-shown-number">{{person.subtitle}}</div>
</div>
<div class="card-number">{{collection.length - (collection.indexOf(person))}}/{{collection.length}}
</div>
</div>
<div class="container like-dislike" >
<div class="circle x" ng-click="clickDisike()"></div>
<div class="icon-like" ng-click="clickLike()"></div>
<div class="clearfix"></div>
</div>
</div><!-- end person-->
<div class="clearfix"></div>
Controller.js
angular.module('black-label', ['ngTouch', 'ngSwippy'])
.controller('MainController', function($scope, $timeout, $window) {
$scope.cardsCollection = [
{
thumbnail: 'images/deck/thor_01.jpg',
collection: 'thoroughbred',
}, {
thumbnail: 'images/deck/thor_02.jpg',
collection: 'thoroughbred',
},
];
// Do the shuffle
var shuffleArray = function(array) {
var m = array.length,
t, i;
// While there remain elements to shuffle
while (m) {
// Pick a remaining element
i = Math.floor(Math.random() * m--);
// And swap it with the current element.
t = array[m];
array[m] = array[i];
array[i] = t;
}
return array;
};
$scope.deck = shuffleArray($scope.cardsCollection);
$scope.myCustomFunction = function(person) {
$timeout(function() {
$scope.clickedTimes = $scope.clickedTimes + 1;
$scope.actions.unshift({ name: 'Click on item' });
$scope.swipeRight(person);
});
};
$scope.clickLike = function(person) {
console.log($scope.count);
// swipeRight(person);
};
$scope.count = 0;
$scope.showinfo = false;
$scope.clickedTimes = 0;
$scope.actions = [];
$scope.picks = [];
var counterRight = 0;
var counterLeft = 0;
var swipes = {};
var picks = [];
var counts = [];
var $this = this;
$scope.swipeend = function() {
$scope.actions.unshift({ name: 'Collection Empty' });
$window.location.href = 'theme-default.html';
};
$scope.swipeLeft = function(person) {
//Essentially do nothing
$scope.actions.unshift({ name: 'Left swipe' });
$('.circle.x').addClass('dislike');
$('.circle.x').removeClass('dislike');
$(this).each(function() {
return counterLeft++;
});
};
$scope.swipeRight = function(person) {
$scope.actions.unshift({ name: 'Right swipe' });
// Count the number of right swipes
$(this).each(function() {
return counterRight++;
});
// Checking the circles
$('.circle').each(function() {
if (!$(this).hasClass('checked')) {
$(this).addClass('checked');
return false;
}
});
$('.icon-like').addClass('liked');
$('.icon-like').removeClass('liked');
$scope.picks.push(person.collection);
// console.log('Picks: ' + $scope.picks);
// console.log("Counter: " + counterRight);
if (counterRight === 4) {
// Calculate and store the frequency of each swipe
var frequency = $scope.picks.reduce(function(frequency, swipe) {
var sofar = frequency[swipe];
if (!sofar) {
frequency[swipe] = 1;
} else {
frequency[swipe] = frequency[swipe] + 1;
}
return frequency;
}, {});
var max = Math.max.apply(null, Object.values(frequency)); // most frequent
// find key for the most frequent value
var winner = Object.keys(frequency).find(element => frequency[element] == max);
$window.location.href = 'theme-' + winner + '.html';
} //end 4 swipes
}; //end swipeRight
});
Any thoughts and help is greatly appreciated!
The ng-click directive is inside an ng-repeat directive inside a directive with isolate scope. To find the clickLike() function it needs to go up two parents:
<!--
<div class="icon-like" ng-click="clickLike()"></div>
-->
<div class="icon-like" ng-click="$parent.$parent.clickLike()"></div>
For information, see AngularJS Wiki - Understanding Scopes.

Directive's code fires before I got data

This is continuation of this question Get other columns from select ng-options
I have the problems with my directive. First problem is that with the very first initial load of the form I can see correctly department and category, but item shows 'Select Item' instead of the item. The second problem is when I navigate to another row in the list, the initial values are not shown (e.g. everything is showing 'Select Department', 'Select Category', 'Select Item' instead of the values. I confirmed that in that situation I didn't retrieve the row's data yet. So, I need to run directive's code only after I got my data.
How can I resolve my problems?
Here is the whole code for the directive:
(function () {
'use strict';
var app = angular.module('sysMgrApp');
app.directive('smDci', ['departmentService', 'categoryService', 'itemService', smDci]);
function smDci(departmentService, categoryService, itemService) {
var directive = {
restrict: 'E',
scope: {
selectedDepartmentId: '=?departmentid',
selectedCategoryId: '=?categoryid',
selectedItemId: '=itemid',
selectedDci: '=?dci'
},
controller: ['$scope', 'departmentService', 'categoryService', 'itemService',
function ($scope, departmentService, categoryService, itemService) {
$scope.selectedDepartmentId = $scope.selectedDepartmentId || 0;
$scope.selectedCategoryId = $scope.selectedCategoryId || 0;
$scope.selectedItemId = $scope.selectedItemId || 0;
$scope.selectedDci = $scope.selectedDci || '';
var init = function () {
$scope.metaData = {};
window.console && console.log('Selected departmentId = ' + $scope.selectedDepartmentId +
' Selected categoryId = ' + $scope.selectedCategoryId + ' Selected ItemId = ' + $scope.selectedItemId);
departmentService.getAllDepartments().then(function (data) {
$scope.metaData.departments = data.departments;
//window.console && console.log('Got all departments...')
});
if ($scope.selectedDepartmentId == 0 && $scope.selectedCategoryId == 0 && $scope.selectedItemId != 0) {
itemService.getItemById($scope.selectedItemId).then(function (data) {
var item = data.item;
if (item != null) {
$scope.selectedItem = item;
$scope.selectedDepartmentId = item.departmeId;
$scope.selectedCategoryId = item.categoryId;
window.console && console.log('Initial selections are about to fire...')
getInitialSelections();
}
});
}
else {
getInitialSelections();
}
};
var getInitialSelections = function()
{
if ($scope.selectedDepartmentId != 0) {
$scope.departmentChanged($scope.selectedDepartmentId);
}
if ($scope.selectedCategoryId != 0) {
$scope.categoryChanged($scope.selectedCategoryId);
}
}
$scope.departmentChanged = function (departmentId) {
if (!departmentId) {
$scope.selectedCategoryId = '';
$scope.selectedItemId = '';
$scop.selectedItem = {};
$scope.selectedDci = '';
}
else
{
categoryService.getCategoriesByDepartmentId(departmentId).then(function (data) {
$scope.metaData.categories = data.categories;
//window.console && console.dir($scope.selectedItem);
});
}
};
$scope.categoryChanged = function (categoryId) {
if (!categoryId) {
$scope.selectedItemId = '';
$scope.selectedItem = null;
$scope.selectedDci = '';
}
else
{
itemService.getItemsByCategoryId(categoryId).then(function (data) {
$scope.metaData.items = data.items;
});
}
};
$scope.itemChanged = function(item)
{
$scope.selectedItemId = item.itemId;
$scope.selectedDci = item.department + item.category + item.item;
}
init();
}],
templateUrl: 'app/templates/smDci'
};
return directive;
}
})();
and its HTML:
<div class="row">
<label class="control-label col-md-2" title="#Labels.dci">#Labels.dci:</label>
<div class="col-md-3">
<select class="form-control" ng-model="selectedDepartmentId" name="department" id="department"
ng-options="d.departmeId as d.descrip for d in metaData.departments"
data-no:dirty-check
ng-change="departmentChanged(selectedDepartmentId)">
<option value="">#String.Format(Labels.selectX, Labels.department)</option>
</select>
</div>
<div class="col-md-3">
<select class="col-md-3 form-control" ng-model="selectedCategoryId" id="category" name="category"
ng-disabled="!selectedDepartmentId"
data-no:dirty-check
ng-change="categoryChanged(selectedCategoryId)"
ng-options="c.categoryId as c.descrip for c in metaData.categories | filter: {departmeId:selectedDepartmentId}">
<option value="">#String.Format(Labels.selectX, Labels.category)</option>
</select>
</div>
<div class="col-md-3">
<select class="col-md-3 form-control" ng-model="selectedItem" id="item" name="item"
ng-disabled="!selectedCategoryId"
ng-change="itemChanged(selectedItem)"
ng-options="c as c.descrip for c in metaData.items | filter: {departmeId:selectedDepartmentId, categoryId:selectedCategoryId}">
<option value="">#String.Format(Labels.selectX, Labels.item)</option>
</select>
<div class="field-validation-error">
<span ng-show="item.$error.required">#String.Format(Messages.isRequired, Labels.item)</span>
</div>
</div>
</div>
<div class="clearfix"></div>
And this is how I use it in the form:
<data-sm:dci itemid="currentCardAct.itemId" dci="currentCardAct.dci"></data-sm:dci>
Using the logging to console I can see that card data retrieved after I need, e.g. in the console I see
Selected departmentId = 0 Selected categoryId = 0 Selected ItemId = 0
CardActController.js:221 Current Card Activity data retrieved..
smDci.js:28 Selected departmentId = 0 Selected categoryId = 0 Selected ItemId = 0
CardActController.js:221 Current Card Activity data retrieved..
I guess I can add watches in the directive's code, but is it the only option?
I solved the problem by adding a watch. I'm now trying to solve the problem with the initial selection of the item and apparently it's a known problem as referenced here http://odetocode.com/blogs/scott/archive/2013/06/19/using-ngoptions-in-angularjs.aspx about initial selection.

Angular js bind local array with global scope

I have an angular form. only 2 input box. I am taking the
values from input box and then saving them in an array.
then the problem begins.
I want to show the array wrapped with <pre></pre> tag
how do I do that. Code sample is like this.
<input type="text" class="form-control" id="qus" placeholder="Enter Question" ng-model="qus">
<input type="text" class="form-control" id="op1" placeholder="Option 1" ng-model="op1">
<label><input type="checkbox" ng-model="correct1">Correct</label>
<button class="form-control btn btn-primary" ng-click = "save()">Save</button>
<pre ng-bind="dataShow"></pre>
Script:
var app = angular.module('qApp', []);
app.controller('qCtrl', function($scope) {
var set = [];
var op1 = [];
$scope.save = function (){
if($scope.correct1!==true){$scope.correct1=false;}
op1.push($scope.op1, $scope.correct1);
var qus = [$scope.qus, op1];
set.push(qus);
console.log(qus);
console.log(set);
return set;
};
$scope.dataShow = set.toString();
});
Move $scope.dataShow = set.toString(); inside the function and remove the return:
$scope.save = function () {
var set = [];
var op1 = [];
if ($scope.correct1 !== true) {
$scope.correct1 = false;
}
op1.push($scope.op1, $scope.correct1);
var qus = [$scope.qus, op1];
set.push(qus);
console.log(qus);
console.log(set);
$scope.dataShow = set.toString();
};

Categories

Resources