AngularJS not updating? - javascript

I'm not sure why this is not changing when its bound object changes:
My HTML:
<div id="account-info" ng-controller="AuthenticateCtrl">
<h5>Account: </h5>
{{account}}
</div>
<div ng-controller="AuthenticateCtrl">
<div modal="shouldBeOpen" options="opts">
<div class="modal-header">
<h3>Select your account</h3>
</div>
<div class="modal-body">
<div class="account-btn" ng-repeat="item in items" ng-click="close(item)">
{{item}}
</div>
</div>
</div>
</div>
My JavaScript:
var AuthenticateCtrl = function ($scope) {
$scope.account= "";
$scope.open = function() {
$scope.shouldBeOpen = true;
};
$scope.close = function(item) {
if (item) {
$scope.shouldBeOpen = false;
$scope.account= item;
}
};
}
For some reason it always displays nothing, or if I set $scope.account = "ANY STRING" it will display "ANY STRING" but won't update when the close function is called.

Ok an attempt with fiddle. Firstly you had two ng-controller directives pointing to the same function. Secondly I don't really understand the domain here, but I'm guessing this is what you need. Heres a fiddle.
<div ng-controller="AuthenticateCtrl">
<div id="account-info">
<h5>Account: </h5>
{{account.name}}
</div>
<div>
<div modal="shouldBeOpen" options="opts">
<div class="modal-header">
<h3>Select your account</h3>
</div>
<div class="modal-body">
<div class="account-btn" ng-repeat="item in items" ng-click="close(item)">
{{item.name}}
</div>
</div>
</div>
</div>
</div>
<script>
var myApp = angular.module('myApp',[]);
var AuthenticateCtrl = function ($scope) {
$scope.opts = {};
$scope.account = {};
$scope.items = [
{'name':'one'},
{'name':'two'}
];
$scope.open = function() {
$scope.shouldBeOpen = true;
};
$scope.close = function(item) {
if (item) {
$scope.shouldBeOpen = false;
$scope.account= item;
}
};
}
</script>

Related

Return false Angular code if text area is empty

var myApp = angular.module("myApp", []);
myApp.controller("votesController", ['$scope', function($scope, $timeout) {
$scope.comments = [
];
$scope.newComment = {
likes: 0
};
$scope.createComment = function() {
if ($scope.newComment.comment != "") {
$scope.comments.push({
comment: $scope.newComment.comment,
likes: $scope.newComment.likes,
likeColor : {},
dislikeColor : {}
});
}
};
$scope.incrementLikes = function(comment) {
comment.likes++;
};
$scope.decrementLikes = function(comment) {
comment.likes--;
};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="container" ng-app="myApp">
<div ng-controller="votesController">
<div ng-repeat="comment in comments">
<div class="comment_box_all">
<div class="comment_user">
<div class="comment_note">
<a id="vote_comment" ng-click="incrementLikes(comment, $index)" class="vote_comment" ng-style="comment.likeColor">Like</a>
<span class="num_vote_comm_11"> | {{comment.likes}} | </span>
<a ng-click="decrementLikes(comment, $index)" class="vote_dis_like_comm" ng-style="comment.dislikeColor">Unlike</a>
</div>
<div class="content_text_user_ans"><span>{{comment.comment}}</span></div>
</div>
</div>
</div>
<div class="area_comm_tex">
<textarea class="text_area" ng-model="newComment.comment" placeholder="Add comment"></textarea>
<button class="op_comm_now" ng-click="createComment()">Add text</button>
</div>
</div>
</div>
Hey, now this is script which add text and can count like or dislike click, but is one problem, this code worsk even if text area is empty (like/dislike is added).
Question: How do that if text area is empty(no any characters, e.g. trim()) this code no works just like return false ?
You should init your $scope.newComment.comment to make it not undefined.
var myApp = angular.module("myApp", []);
myApp.controller("votesController", ['$scope', function($scope, $timeout) {
$scope.comments = [
];
$scope.newComment = {
likes: 0,
comment:""
};
$scope.createComment = function() {
if ($scope.newComment.comment != "") {
$scope.comments.push({
comment: $scope.newComment.comment,
likes: $scope.newComment.likes,
likeColor : {},
dislikeColor : {}
});
}
};
$scope.incrementLikes = function(comment) {
comment.likes++;
};
$scope.decrementLikes = function(comment) {
comment.likes--;
};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="container" ng-app="myApp">
<div ng-controller="votesController">
<div ng-repeat="comment in comments">
<div class="comment_box_all">
<div class="comment_user">
<div class="comment_note">
<a id="vote_comment" ng-click="incrementLikes(comment, $index)" class="vote_comment" ng-style="comment.likeColor">Like</a>
<span class="num_vote_comm_11"> | {{comment.likes}} | </span>
<a ng-click="decrementLikes(comment, $index)" class="vote_dis_like_comm" ng-style="comment.dislikeColor">Unlike</a>
</div>
<div class="content_text_user_ans"><span>{{comment.comment}}</span></div>
</div>
</div>
</div>
<div class="area_comm_tex">
<textarea class="text_area" ng-model="newComment.comment" placeholder="Add comment"></textarea>
<button class="op_comm_now" ng-click="createComment()">Add text</button>
</div>
</div>
</div>
You could do something like this:
$scope.incrementLikes = function(comment) {
if(comment.comment != null && comment.comment.length > 0) comment.likes++;
};
$scope.decrementLikes = function(comment) {
if(comment.comment != null && comment.comment.length > 0) comment.likes--;
};
var myApp = angular.module("myApp", []);
myApp.controller("votesController", ['$scope', function($scope, $timeout) {
$scope.comments = [
];
$scope.newComment = {
likes: 0
};
$scope.createComment = function() {
if ($scope.newComment.comment != "") {
$scope.comments.push({
comment: $scope.newComment.comment,
likes: $scope.newComment.likes,
likeColor : {},
dislikeColor : {}
});
}
};
$scope.incrementLikes = function(comment) {
if($scope.newComment.comment && $scope.newComment.comment.length){
comment.likes++;
}
};
$scope.decrementLikes = function(comment) {
if($scope.newComment.comment && $scope.newComment.comment.length){
comment.likes--;
}
};
}]);
you checked first whether text is empty.if text is empty.donot do increment or decrement.

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>

Error: message.$delete is not a function

I'm trying to send a DELETE request by using the angular-resource service, but I keep getting the following message in dev tools:
Error: message.$delete is not a function
$scope.deleteMessage#file:///Users/me/Desktop/angular/my-app/loyalty-program_messages-pointstransactions.js:37:13
anonymous/fn#file:///Users/me/Desktop/angular/my-app/angularjs/angular.js line 14605 > Function:2:329
expensiveCheckFn#file:///Users/me/Desktop/angular/my-app/angularjs/angular.js:15694:18
ngEventHandler/https://code.jquery.com/jquery-1.12.4.min.js:3:12392
n.event.add/r.handle#https://code.jquery.com/jquery-1.12.4.min.js:3:9156
I notice that the angular-resource is missing here. Is there a reason for this?
This is the module with the controller:
var myApp = angular.module('myApp', ['ngResource'])
.constant("baseUrl1", MY-TESTING-URL-1)
.config(function($httpProvider) {
$httpProvider.defaults.withCredentials = true;
})
myApp.controller("MessagesCtrl", function($scope, $http, $resource, baseUrl1){
$scope.displayMode = "list";
$scope.currentMessages = null;
$scope.messagesResource = $resource(MY-TESTING-URL-1 + ":id?projection=full", { id: "#id" });
$scope.listMessages = function () {
$scope.foo = $scope.messagesResource.get();
$scope.foo.$promise.then(function (data) {
$scope.messages = [];
for(var i = 0; i < $scope.foo._embedded.messages.length; i++) {
var obj = $scope.foo._embedded.messages[i];
$scope.messages.push(obj);
}
});
}
$scope.deleteMessage = function (message) {
message.$delete().then(function () {
$scope.messages.splice($scope.messages.indexOf(message), 1);
});
$scope.displayMode = "list";
}
$scope.createMessage = function (message) {
new $scope.messagesResource(message).$save().then(function(newMessage) {
$scope.messages.push(newMessage);
$scope.displayMode = "list";
});
}
$scope.updateMessage = function (message) {
message.$save();
$scope.displayMode = "list";
}
$scope.editOrCreateMessage = function (message) {
$scope.currentMessage = message ? message : {};
$scope.displayMode = "edit";
}
$scope.saveEdit = function (message) {
if (angular.isDefined(message.id)) {
$scope.updateMessage(message);
} else {
$scope.createMessage(message);
}
}
$scope.cancelEdit = function () {
if ($scope.currentMessage && $scope.currentMessage.$get) {
$scope.currentMessage.$get();
}
$scope.currentMessage = {};
$scope.displayMode = "list";
}
$scope.listMessages();
});
This is the view with the ng-click that SHOULD send a DELETE request:
<div ng-repeat="message in messages">
<div class="data-tables read-{{ message.read }}">
<div class="data-tables-rows">
<div class="data-tables-toggle" type="button" data-toggle="collapse" data-target="#collapse_disclaimer_data-table_message-center_{{ $index }}" aria-expanded="false" aria-controls="collapse_disclaimer_data-table_message-center_{{ $index }}" title="View Details">
<label></label>
</div>
<div class="data-table-message hidden-xs" type="button" data-toggle="collapse" data-target="#collapse_disclaimer_data-table_message-center_{{ $index }}" aria-expanded="false" aria-controls="collapse_disclaimer_data-table_message-center_{{ $index }}" title="View Details">
<p style="white-space: nowrap; width: inherit; overflow: hidden;text-overflow: ellipsis;"><b>message</b><br />
{{ message.message }}
</p>
</div>
<div class="data-table-date" type="button" data-toggle="collapse" data-target="#collapse_disclaimer_data-table_message-center_{{ $index }}" aria-expanded="false" aria-controls="collapse_disclaimer_data-table_message-center_{{ $index }}" title="View Details">
<p><b>date</b><br />
<date>{{ message.dateReceived | date }}</date>
</p>
</div>
<div class="data-table-points hidden-xs points-{{ message.metadata }}" type="button" data-toggle="collapse" data-target="#collapse_disclaimer_data-table_message-center_{{ $index }}" aria-expanded="false" aria-controls="collapse_disclaimer_data-table_message-center_{{ $index }}" title="View Details">
<p><b>Points</b><br />
{{ message.metadata }}</p>
</div>
<div class="data-table-delete">
<button ng-click="deleteMessage(message)">Delete</button>
</div>
</div>
<div class="collapse" id="collapse_disclaimer_data-table_message-center_{{ $index }}">
<div class="data-tables-rows">
<div class="data-tables-spacer" style="visibility:hidden;">
<input id="data-table-icon" type="checkbox" />
<label for="data-table-icon"></label>
</div>
<div class="well">
<div class="data-table-message">
<p><b>Message</b><br />
{{ message.message }}</p>
</div>
<div class="data-table-points visible-xs">
<p><b>Points</b><br />
{{ message.metadata }}</p>
</div>
</div>
<div class="data-tables-spacer">
</div>
</div>
</div>
</div>
The message comes from CDN served JSON:
{
"_embedded": {
"messages":
{
"id": 8,
"message": "You received points",
"dateReceived": "2016-08-01T00:00:00.000+0000",
"read": false,
"metadata": "50"
}
}
}
Firefox in debugger option 'Selection to watch expression' doesn't appear to reveal anything abnormal as the object data is listed. Please help!
Thank you Joaozito Polo, you helped us figure it out. var newMessage is the new object from resource. Here is the new listMessages function:
$scope.listMessages = function () {
$scope.foo = $scope.messagesResource.get();
$scope.foo.$promise.then(function (data) {
$scope.messages = [];
for(var i = 0; i < $scope.foo._embedded.messages.length; i++) {
var obj = $scope.foo._embedded.messages[i];
var newMessage = new $scope.messagesResource(obj)
$scope.messages.push(newMessage);
}
});
}

Can't hide div in angularjs

When clicking module class it shows emptylabel. but i cant hide the module class.
<div id="b" class="tab-pane fade in active" >
<div class="secondrow">
<div ng-show="divshow">
<label class="emptylabel"> <input type="button" value="back" class="backbutton" ng-click="hidediv()"></label>
</div>
<div class="module">
<a href="#/b" class="{{module}}" ng-click="showdiv()">
<div class="col-sm-4"><label>Jawaharlal Nehru</label></div>
<div class="col-sm-1"><label>111111</label></div>
<div class="col-sm-2"><label>2222222</label></div>
<div class="col-sm-3"><label>3333333</label></div>
</a>
</div>
Controller:
app.controller('myController', ['$scope', function($scope) {
$scope.showdiv = function () {
$scope.divshow = true;
$scope.module = false;
}
// Hide Div
$scope.hidediv = function () {
$scope.divshow = false;
}
}]);
I'm not sure if I understand your question correctly. If you want to toggle between the emptylabel and module, the you can use ng-show for both of them, based on the divshow variable:
<div ng-show="divshow">
<label class="emptylabel">
<input type="button" value="back" class="backbutton" ng-click="hidediv()">
</label>
</div>
<div class="module" ng-show="!divshow">
<a href="#/b" class="{{module}}" ng-click="showdiv()">
...
</a>
</div>
controller:
app.controller('myController', ['$scope', function($scope) {
$scope.showdiv = function () {
$scope.divshow = true;
}
$scope.hidediv = function () {
$scope.divshow = false;
}
}]);
What does your ng-controller declaration in the HTML look like? For example mine usually look something like this, with the capture variable 'vm':
<div data-ng-controller="FooController as vm">
<div>
<span data-ng-click="vm.showDiv()"></span>
</div>
</div>
Inside your controller:
function FooController() {
var vm = this;
vm.showDiv = showDiv;
function showdiv() {
// Your code here
}
}

How do I update a view after ng-submit calls a factory function?

$scope.temp and $scope.description don't have values until ng-submit calls $scope.getWeather. I can log the values after submission, but can't update the view to display them. $scope.test is demonstrating that my view will only display "This is a DEFAULT value" and not update to "This is the NEW value" when $scope.getWeather is called. Thanks.
angular.module('forecastCtrl', ['weatherService'])
.controller('forecastController', function($http, $scope, Weather) {
//var vm = this;
$scope.test = 'This is a DEFAULT value';
$scope.getWeather = function(postData) {
Weather.get(postData)
.success(function(data) {
console.log(data);
$scope.test = 'This is the NEW value';
$scope.temp = data.query.results.channel.item.condition.temp;
$scope.description = data.query.results.channel.item.condition.text;
})
.error(function(error) {
console.log(error);
});
event.preventDefault();
};
// THIS IS THE FORM
<form name="getWeatherForm" action="#" ng-submit="getWeather(postData)" class="small-10 large-6 small-centered large-centered columns">
<div class="row collapse">
<div class="small-9 columns">
<input type="text" placeholder="Philadelphia, PA" ng-model="postData.city">
</div>
<div class="small-3 columns">
<button type="submit" class="button postfix">Go</button>
</div>
</div>
</form>
//THIS IS THE FACTORY
angular.module('weatherService', [])
.factory('Weather', function($http) {
return {
get: function(location) {
location = location.city;
location = location.replace(/\s/g, '');
// do error handling
return $http.get('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22'+location+'%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys');
}
}
});
// THE VIEW
<main id="content">
<div class="row">
<div class="small-12 large-12 columns">
<section class="wrapper">
{{ test }}
<h1>{{ forecast.temp }}</h1>
<h2>{{ forecast.description }}</h2>
</section>
</div>
</div>
The code is working, but the repsonse does not have the assumed properties when the city is not provided or wrong city is provided. So maybe use ng-required, as the code will fail if the postData.city is not set
http://plnkr.co/edit/7F3EUMyAXtAlBR9CGWb0?p=preview
.success(function(data) {
console.log(data);
$scope.test = 'This is the NEW value';
$scope.temp = data.query.results.channel.item.condition.temp;

Categories

Resources