Angularjs not updating variables - angularjs

I want to display/update the calculation answer directly without the need of aditional buttons.
Or do i need a function and button to apply the changes?
<div ng-app="myApp" ng-controller="myCtrl">
A_Number: <input type="number" step="1" ng-model="A_Number"><br>
Display (A_Number): {{A_Number}}
<br>
square: {{square}}
</div>
controller:
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.square = $scope.A_Number * $scope.A_Number;
});
</script>

Make square as a method & use that method in interpolation directive, so that will evaluate on each digest.
Markup
square: {{square()}}
Code
$scope.square = function(){
//made error free
if(!isNaN($scope.A_Number))
return $scope.A_Number * $scope.A_Number;
return 0;
};

Add watch on A_Number to achieve the same. JSFiddle for reference -
https://jsfiddle.net/9a2xz61y/3/
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.square = 0;
$scope.$watch('A_Number', function(newValue, oldValue) {
{
if (!isNaN(newValue)) {
$scope.square = $scope.A_Number * $scope.A_Number;
}
}
});
});

Related

How to hide some element on screen resize in angularjs

I am new in angularjs. I searched a lot to hide some html element on body resize but did't work. here is my controller code.
var app = angular.module('studentPage',[]);
app.controller ('studentController',function($scope, $window) {
var appWindow = angular.element($window);
appWindow.bind('resize', function () {
if($window.innerWidth < 600){
alert("hello");
$scope.ohh = true;
}
});
});
and here where i use ng-show
<div id="sidebar-wrapper" ng-show="ohh">
If you want to achieve this using AngularJS, you need to relaunch the digest cycle using $scope.$apply().
appWindow.bind('resize', function () {
if($window.innerWidth < 600){
$scope.ohh = true;
$scope.$apply();
}
});
Anyway, I think a cleaner way to do that is using CSS media queries:
#media only screen and (max-width: 599px) {
#sidebar-wrapper {
display: none;
}
}
You have to manually trigger the digest cycle using $apply() function , since what you are doing is out of angular context.Try the below code.
var app = angular.module('studentPage',[]);
app.controller ('studentController',function($scope, $window) {
var appWindow = angular.element($window);
appWindow.bind('resize', function () {
if($window.innerWidth < 600){
alert("hello");
$scope.ohh = true;
$scope.$apply()
} });});
You have to apply the scope changes by calling $scope.$apply().:-
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope, $window) {
var appWindow = angular.element($window);
$scope.ctrl = {};
$scope.ctrl.ohh = false;
appWindow.bind('resize', function() {
console.log($window.innerWidth);
if ($window.innerWidth < 600) {
$scope.ctrl.ohh = true;
$scope.$apply()
}
});
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<h1>THis is main content</h1><br>
<div id="sidebar-wrapper" ng-show="ctrl.ohh">This is shown after window width is less than 600
</div>
</div>

angular $watch is not work with d3.js

look, click the button, $scope.optionis change, but $watch is not work, can`t console.log the option value , why?
I am sorry , it is my mistake , but it still is a problem in I use width d3.js
I use d3.js append a rect into page, and I want to when I click the rect can chagne the option value, but $watch is not work, why?
angular.module('myapp',[]).controller('myCtrl', function($scope){
$scope.option = '123';
$scope.d3TreeDraw = {
source : {
name: 'myTree'
},
updata: function(){
var _self = this;
var tree = d3.layout.tree().nodeSize([90, 60]);
var nodes = tree.nodes(_self.source).reverse();
nodes.forEach(function(d) { d.y = d.depth * 90; });
var svg = d3.select("body").append("svg")
.attr("width", 200)
.attr("height", 200)
var node = svg.selectAll("g.node")
.data(nodes)
var nodeEnter = node.enter().append("g")
.attr("class", "node")
.style('cursor','pointer')
.on('click', function(d){
console.log('click'); // can console.log
$scope.option = '456';
console.log($scope.option) //is change
})
nodeEnter.append("rect")
.attr('width',150)
.attr('height', 30)
.style('fill', '#000')
}
}
$scope.d3TreeDraw.updata();
$scope.$watch('option', function(){
console.log('change:' + $scope.option); // when option is change,can not console.log
})
})
1) First You have taken myTree.onClick() and your function has onclick
So, the onClick() spelling mismatched.
Change button to <button ng-click="myTree.onclick()">456</button>
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<button ng-click="myTree.onclick()">{{data}}</button>
<br>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
$scope.data = '100';
$scope.myTree = {
onclick: function() {
$scope.data = '456';
}
}
$scope.$watch('data', function(){
console.log($scope.data);
alert($scope.data);
})
});
</script>
</body>
</html>
Here is a working DEMO.
EDIT:
By checking your edit, I saw that your scope assignment is outside of angular.
So, you need to $apply() the $scope
Change,
$scope.option = '456';
to,
$scope.$apply(function() {
$scope.option = '456'
});
The above method, runs the digest cycle manually, and apply the changes for the scope.
Performance:
If you write $scope.$apply() it will run complete digest cycle, which will affect the performance, so we sent a function into the $apply method and only ran the digest cycle of specific `scope.
Hence, you can $watch the scope whenever you want.
you have a upper case letter in the function name
change this
<button ng-click="myTree.onClick()">456</button>
to this
<button ng-click="myTree.onclick()">456</button>
Demo
angular.module("app",[])
.controller("ctrl",function($scope){
$scope.data = '123';
$scope.$watch('data', function(){
console.log($scope.data);
})
$scope.myTree = {
onclick: function() {
$scope.data = '456';
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<button ng-click="myTree.onclick()">456</button>
</div>

watch rootScope variable to change the progressBar value

app.controller("ListController1", ['$rootScope',function($rootScope) {
$rootScope.progressBar=10;
$rootScope.$watch(
function() {
return $rootScope.progressBar;
},
function(){
alert($rootScope.progressBar);
alert("changed");
},true)
}]);
app.controller("ListController2", ['$scope','$rootScope',function($scope,$rootScope) {
$scope.save=function() {
$rootScope.progressBar=20;
}
}]);
I want progressBar value form ListController2 to be reflected back in Listcontroller1. It seems i am doing something wrong with it. Please help any one. thank u.
Rather than sharing state with $routeScope, you should consider creating a service to share the state of the progress bar - this is one of the use cases of services.
When the save button is pressed in the code below, it updates the value in progressService. The value from progressService is watched in the first controller and the view is updated accordingly.
You can add progressService to as many controllers as you'd like.
var app = angular.module("app", []);
app.factory("progressService", [function() {
var service = this;
service.progressBar = 0;
return service;
}]);
app.controller("ListController1", ["$scope", "progressService", function($scope, progressService) {
progressService.progressBar=10;
$scope.progress = progressService.progressBar;
$scope.$watch(
function() {
return progressService.progressBar;
},
function(newValue) {
$scope.progress = newValue;
});
}]);
app.controller("ListController2", ['$scope','progressService',function($scope,progressService) {
$scope.save=function() {
progressService.progressBar=20;
}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="ListController1">
Progress: {{progress}}
</div>
<div ng-controller="ListController2">
<button ng-click="save()">Save</button>
</div>
</div>

issue with the ng-options not working in a simple array in AngularJS

I want to save the selected value and pop up the selected value . But when I add the ng- change directive the select stops functioning. If you remove the ng change the droplist is displayed. Help me out.
This is my html
<div ng-app="HelloApp">
<div ng-controller="MyCtrl">
<p>Term</p>
<select ng-model="bob" ng-change="test()" ng-options="x for x in nos">
</select>
</div>
</div>
And this is my js script
**var app = angular.module('HelloApp', []);
app.controller('MyCtrl', function($scope) {
console.log('ctrl working');
$scope.test = function () {
nos=["5", "10", "15"];**
var kill=$scope.bob;
alert ("changed!"+ kill);
}
});
I am new to angular and internet searches only land to complex arrays not a simple one. Please help
Change your script to the following :
var app = angular.module('HelloApp', []);
app.controller('MyCtrl', function($scope) {
console.log('ctrl working');
$scope.nos=["5", "10", "15"];
$scope.test = function () {
var kill=$scope.bob;
alert ("changed!"+ kill);
}
});
Things to note :
-The nos must be declared into the controller scope , previously it was not visible to the view.
-It should be out of the test function.
See this -
fiddle
$scope.nos=["5", "10", "15"];
$scope.bob="";
$scope.test = function () {
alert($scope.bob);
}
Just a Bit change , nothing major
app.controller('MyCtrl', function($scope) {
$scope.nos=["5", "10", "15"];
$scope.test = function (x) {
alert (x);
}
});
HTML
<select ng-model="bob" ng-change="test(bob)" ng-options="x for x in nos">
Thanks

Alert() twice in simple angular app

Alert function is firing off twice, I can't figure out why: http://jsfiddle.net/ntzLrkmz/2/
It's going to alert when a !number is inserted at <input type="number">
EDIT: thanks all, I'll be playing with this useful information
This happens because angular evals the list when the times variable change and $diggest to build the ng-reapeat with the new value. You should use $watch instead:
angular.module('helloApp', [])
.controller('helloController', ['$scope', function ($scope) {
$scope.times = 1;
$scope.$watch('times', function (newValue, oldVaue) {
if (!angular.isNumber(newValue)) {
$scope.times = oldVaue;
alert('ENTER A VALID POSITIVE NUMBER PLEASE');
}
});
$scope.getTimes = function (n) {
if (angular.isNumber(n)) {
return new Array(n);
}
};
}]);
Working example here: http://jsfiddle.net/fals/75uv4ugb/
By restructuring your logic and a slight change to your ng-repeat you can solve this issue:
DEMO EXAMPLE
HTML:
<p ng-repeat="obj in array track by $index" ng-show="name.length">Welcome {{name}} !</p>
JS:
angular.module('helloApp', [])
.controller('helloController', ['$scope', function ($scope) {
$scope.array = [];
$scope.populateArray = function (n, t) {
$scope.array = [];
if (t > 0) {
for (i = 0; i < t; i++) {
$scope.array.push(n);
}
}
}
}]);

Resources