Unable to add value in string array in angularjs? - html

I'm trying to add value in students array, but below code isn't working.
js code is --
angular.module('formExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.students=[
'Scarlett Johansson','Jennifer Lawrence','Emma Stone','Kristen Stewart'
];
$scope.add = function(name){
$scope.students.push(name);
};
}]);
html code is --
<body ng-app="formExample">
<div ng-controller="ExampleController">
<p ng-repeat="stud in students">
{{stud}}
</p>
</div>
<input type='text' ng-model="name"/>
<button ng-click="add(name);">add</button>
</body>

Your button and input are not included within the div ng-controller="ExampleController" scope.
<body ng-app="formExample">
<div ng-controller="ExampleController">
<p ng-repeat="stud in students">
{{stud}}
</p>
<input type='text' ng-model="name"/>
<button ng-click="add(name);">add</button>
</div> <!-- close div here -->
</body>

You need to push into $scope.students array, as there is no students array defined in the scope:
$scope.add = function(name) {
$scope.students.push(name);
};

$scope.add = function(name) {
$scope.students.push(name);//
};

Related

Angularjs Parse value from input box to controller

I have an input box of quantity that the user can change it's value by clicking the - and + buttons. The problem is that if I entre the value directly in the input box I can parse this value to my controller. If I change the value by clicking the buttons + or - I can not parse the value to controller, it keeps always the old value. Can anyone help me?
<button
onclick="var result = document.getElementById('qty'); var qty = result.value; if( !isNaN( qty ) && qty > 0 ) result.value--;return false;"
class="reduced items-count"
type="button"
>
<i class="fa fa-minus"> </i>
</button>
<input
type="text"
class="input-text qty"
title="Qty"
maxlength="12"
id="qty"
name="qty"
ng-init="qty='1'"
ng-model="qty"
>
<button
onclick="var result = document.getElementById('qty'); var qty = result.value; if( !isNaN( qty )) result.value++;return false;"
class="increase items-count"
type="button"
>
<i class="fa fa-plus"> </i>
</button>
And my controller,
$scope.$watch('qty', function (val) {
if (val) {
alert("qty2:" + val);
}
});
I don't quite understand what you are trying to implement, but you can use ng-click on your buttons to execute some function in your controller.
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.qty = 0;
$scope.change = function(value) {
$scope.qty += value;
$scope.changed(); // execute after update
}
$scope.changed = function() {
/*
Do what you want after the update,
but $scope.qty is dynamic anyway
*/
//alert("qty: " + $scope.qty);
}
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp">
<div ng-controller="myCtrl">
<button ng-click="change(-1)" type="button">-</button>
<input type="number" ng-model="qty" ng-change="changed()" />
<button ng-click="change(1)" type="button">+</button>
<br/>{{qty}}
</div>
</div>
</body>
</html>
This is totally the wrong approach... never use dom methods in angular app like that.
Use ng-click to modify the ng-model property. Also always follow the golden rule of making sure you have a dot in ng-model
angular
.module('app', [])
.controller('Ctrl', function($scope) {
$scope.data = {
qty: 0
}
$scope.updateQty = function(amt) {
$scope.data.qty += amt
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.5/angular.min.js"></script>
<div ng-app="app" ng-controller="Ctrl">
<button ng-click="updateQty(-1)">-1</button>
<input ng-model="data.qty">
<button ng-click="updateQty(1)">+1</button>
</div>

type error : Cannot read value 'name' of undefined

I'm working with Angularjs and firebase to create an app that is a task timer. I create the firebase object and all works fine except when I try to log task.newTask to the console. Here's a bit of my code (please note this is not all the code):
//HTML
<aside id="sidebar">
<section id="widget_1">
<h2 class="titles">Task History:</h2>
<input id="text-field" type="text" ng-model="taskText" />
<input id="task-button" type="button" value="Add Task" ng-click="addTask()" />
</section>
<section id="widget_2">
<h2 class="titles">Task List:</h2>
<table>
<tr ng-repeat="task in timer_tasks | orderBy: '-taskText'">
<td>{{ task.taskText }}</td>
</tr>
</table>
</section>
</aside>
//Controller:
(function() {
'use strict'
function HomeCtrl($scope, $firebaseArray, $interval) {
console.log('I see you home controller ... you are loaded sir!!!')
var timerRef = firebase.database().ref().child('timer_tasks');
$scope.timer_tasks = $firebaseArray(timerRef);
$scope.addTask = function () {
$scope.timer_tasks.$add({
taskText: $scope.taskText,
newTask: true
}).then(function (timerRef) {
$scope.taskText = '';
});
};
console.log(task.newTask);
On page load the error comes up at console.log(task.newTask);
Any help would be great. Thanks in advance!
If i'm understood correctly, you need to retrieve textbook value in controller which will build $scope.timer_tasks and later can be retrieved back to view in ng-repeat.
view
<aside id="sidebar">
<section id="widget_1">
<h4 class="titles">Task History:</h4>
<input id="text-field" type="text" ng-model="taskText" />
<input id="task-button"
type="button"
value="Add Task"
ng-click="addTask(taskText)"/>
</section>
</aside>
Script
myApp.controller('myCtrl', function($scope) {
$scope.addTask = function (value) {
console.log(" clicked : "+value);
};
});
All i did was bind the value upon addTask click from ng-model to ng-click and as you can see now you have that value in addTask function.

AngularJS $rootScope not accessible in html page

I have looked for the solution in following two links:
how-to-access-rootscope-value-defined-in-one-module-into-another-module
rootscope-variable-exists-but-not-accessible
But still could not find a solution.
I initialize $rootScope.user variable in $scope.login function, which is triggered by some other button click event, of my controller as:
app.controller('LoginFormController',['$rootScope','$location','$log','$scope','userAngService','userBean',function($rootScope,$location,$log,$scope,userAngService,userBean){
$scope.login = function(val){
$scope.user = userAngService.login(val).then(function(data){
$rootScope.user = data;
$location.path("/home");
});
};
}]);
Redirecting it to /home mapped in app.js as:
angular.module('Writer', ['AllControllers','ngRoute'])
.config(['$routeProvider', function($routeProvider,$Log){
$routeProvider.when('/Diary',{
templateUrl:'login.html',
controller: 'LoginFormController'
})
.when('/home',{
templateUrl: 'home.html',
controller: 'ReachController'
})
.otherwise({redirectTo : '/Diary'});
}]);
Now I am accessing $rootScope.user variable in the mapped controller ReachController as:
app.controller('ReachController',['$scope','$rootScope',function($scope,$rootScope){
$scope.user = {};
$scope.user = $rootScope.user;
console.log($scope.user);
}]);
It is perfectly logging angular object in console but is not avaiable in my home.html page.
Here is the html page - accessing it in <h2> and <h3> tags:
<div>
<h2>{{$scope.user}}hhhello</h2>
<h3>{{$scope.user.author}}</h3>
<div id="welcomeStory">
<span id="wsTitleBub">Title</span>
<input id="wsTitle" type="text" ng-model="wsPublish.welcomeStoryTitle" />{{wsPublish.welcomeStoryTitle}}
<h6>Words..</h6>
<textarea id="wsWords" ng-model="wsPublish.welcomeStoryWords"></textarea>
<input id="wsPublish" type="button" name="wsPublish" value="Publish" ng-click="pub = !pub" />
<input id="wsAddShelf" type="button" name="wsAddToShelf" value="Add To Shelf" ng-click="addToShelf()" />
</div>
<div id="wsPublishTo" ng-show="pub">
<ul>
<li>
<input type=submit id="wsgroups" value="Group" ng-click="publishGroup(wsPublish)" />
</li>
<li>
<button id="wsPublic" ng-click="public()">Public</button>
</li>
</ul>
</div>
</div>
Just change your $scope.user to user in your markup and it'll work.
Once it is in $rootScope you can directly access it in markup with {{user}} no need to again assign it to scope variable!

Showing previously selected items in drop down menu

Using angular and angular-xeditable I have a drop down menu with a number of options from which to select in the 'amenities' array.
Once I save the selections from the drop down and saved them, I want to make it possible for the user to come back to the page and edit previously selected items.
HTML:
<select multiple class="w-select am-dropdown" size="12" data-ng-model="Amenities"
data-ng-options="amenity.amenity for amenity in amenities" required=""></select>
JS:
$scope.amenities = [{amenity: coffee}, {amenity: beer}, {amenity: parking}];
$scope.Amenities = [];
$scope.selectedAmenities = [coffee, beer];//these are amenities saved in the
database that I want to be able to show as selected using the editable form
Have a case as same as this
Add $scope.$watch to put selected value to $scope.selectedValues as below
$scope.$watch('selectedAmenities ', function (nowSelected) {
$scope.selectedValues = [];
if (!nowSelected) {
return;
}
angular.forEach(nowSelected, function (val) {
$scope.selectedValues.push(val.amenity.toString());
});
});
And then use it like below:
select multiple ng-model="selectedValues" class="w-select am-dropdown" size="12" >
<option ng-repeat="amenity in amenities" value="{{amenity.amenity}}" ng-selected="{{selectedValues.indexOf(amenity.amenity)!=-1}}">{{amenity.amenity}}</option>
</select>
Full code at Plunker
Hope it helps you.
do u mean this?
var m = angular.module('m', []).controller('c', ['$scope',
function($scope) {
$scope.avilibleValues = ['a1', 'a2', 'a3', 'a4', 'a5'];
$scope.selected = [];
$scope.last = 'a1';
$scope.selecting = 'a1';
$scope.select = function(it) {
console.log('select:' + it);
$scope.selecting = it;
};
$scope.change = function() {
console.log($scope.last);
$scope.last && $scope.selected.push($scope.last);
$scope.last = $scope.selecting;
};
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="script.js"></script>
<div ng-app="m">
<div ng-controller="c">
<div class="row">
<label>seleted:</label>
<div>
<p ng-repeat="it in selected">
<a ng-click="select(it)">{{it}}</a>
</p>
<div>
</div>
<div class="row">
<label>selet</label>
<select ng-model="selecting" ng-options=" i for i in avilibleValues" ng-change="change()"></select>
</div>
</div>
</div>
<p>
selecting:{{selecting}}
<p>
selected:{{selected}}
<p>
last:{{last}}
<p>
</div>
</div>

How do I update the model on click only (angular-strap typeahead and json)

I'm having trouble figuring out how to have dynamic data only update when the user selects from the typeahead menu or clicks the search button.
Right now, the dynamic content pertaining to the search query updates automatically when the input value is changed (content disappears). I want the content to stay in view until a new selection has been either clicked in the typeahead list or clicked by the search button.
Any insight at all would be greatly appreciated! Thank you!
Plunker demo:
http://plnkr.co/edit/jVmHwIwJ0KOKCnX6QjVa?p=preview
Code:
<!-- HTML -->
<body ng-controller="MainController">
<!-- Search -->
<div class="well">
<p>Search the term "content"</p>
<form role="form">
<div class="form-group clearfix search">
<input type="text" ng-model="selectedContent" ng-options="query as query.searchQuery for query in searchData" bs-typeahead="bs-typeahead" class="form-control search-field"/>
<button type="button" class="btn btn-primary search-btn"><span class="glyphicon glyphicon-search"></span></button>
</div>
</form>
</div>
<!-- Dynamic Content -->
<div class="well">
<h4>{{ selectedContent.contentTitle }}</h4>
<ul>
<li ng-repeat="item in selectedContent.headlines">{{item.headline}}</li>
</ul>
</div>
<!-- typeahead template -->
<ul class="typeahead dropdown-menu" tabindex="-1" ng-show="$isVisible()" role="select">
<li role="presentation" ng-repeat="match in $matches" ng-class="{active: $index == $activeIndex}">
</li>
<!-- JS -->
var app = angular.module('demoApp', ['ngAnimate', 'ngSanitize', 'mgcrea.ngStrap'])
.config(function ($typeaheadProvider) {
angular.extend($typeaheadProvider.defaults, {
template: 'ngstrapTypeahead.html',
container: 'body'
});
});
function MainController($scope, $templateCache, $http) {
$scope.selectedContent = '';
$http.get('searchData.json').then(function(response){
$scope.searchData = response.data;
return $scope.searchData;
});
};
You could use a directive such as this:
app.directive('mySearch', function(){
return {
restrict: 'A',
require: 'ngModel',
link: function($scope, $element, $attrs, ngModel){
ngModel.$render = function(){
if (angular.isObject($scope.selectedContent)) {
$scope.clickedContent = $scope.selectedContent;
}
}
$scope.updateModel = function() {
$scope.clickedContent = $scope.selectedContent;
}
}
}
})
plunker
Edit:
I added using the ngModelController. The function you set ngModel.$render to gets called whenever the model updates. If you click the typahead popup, then the model selectedContent will be an object, otherwise it'll be a string. If it's an object (meaning the user clicked the typahead popup) we do the same as we did in the updateModel function.