angularjs, Scope not updating across functions - with ngTouch - javascript

I have a controller with such:
$scope.myVar = 0;
$scope.back = function () {
$scope.myVar--;
};
$scope.next = function () {
$scope.myVar++;
};
If next() (with ngClick) is called 3 times, we get:
//1
//2
//3
but if back() (with ngSwipeLeft) is called it returns
//-1
when I'm obviously expecting
//2
What am I missing here?
update: including ngTouch details - this seems to be the problem.. ngTouch is included.
When I watch the myVar value - its like it exists twice - one with the ngSwipeLeft call, and one with the ngClick call

Your snippet looks fine to me. You need to provide more code, error might be somewhere else. Look at the code below.
<!doctype html>
<html ng-app="myapp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.12/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular-touch.min.js"></script>
<script>
var app = angular.module('myapp',['ngTouch']);
var controller = app.controller('mycontroller', ['$scope',function($scope){
$scope.myVar = 0;
$scope.back = function () {
$scope.myVar--;
};
$scope.next = function () {
$scope.myVar++;
};
}]);
</script>
</head>
<body ng-controller="mycontroller">
<div>
<h1>MyVar: {{myVar}}!</h1>
<input type="button" value="back" ng-click="back()"/>
<input type="button" value="next" ng-click="next()"/>
</div>
</body>
</html>

Ok, so I've figured out my problem - I wasn't providing enough detail in the question - but if someone runs into something similar in the future, heres what was going on:
I was declaring my controller with ng-controller="myCtrl" in the templates, but also using routing, where I declared my controller like:
$routeProvider.when('/', {
templateUrl: 'myUrl.html',
controller: 'myCtrl'
});
This was instantiating the controller twice, and obviously causing problems (although that seemed to the only one to surface for now).
Removing the controller definition from the routing or the view did the trick.

need to see your html not sure about your problem, here is a sample working code,
<div ng-app="myapp">
<div ng-controller="IncDecController">
<span>current value is {{myVar}}</span>
<img src="https://angularjs.org/img/AngularJS-large.png" ng-swipe-left="back()"></img>
<button ng-click="next()">next</button>
</div>
</div>
script:
angular.module('myapp', ['ngTouch'])
.controller('IncDecController', ['$scope', function ($scope) {
$scope.myVar = 0;
$scope.back = function () {
$scope.myVar--;
};
$scope.next = function () {
$scope.myVar++;
};
}])

Related

Angular1 sibling Controllers how can access each others data

I am trying to get FirstCtrl data in SecondCtrl, but there is no response in SecondCtrl, Please help me to solve this
I Have tried to use $broadcast and $emit on $rootscope. but there is not data coming on $on
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script>
var myApp = angular.module('myApp', []);
myApp.controller('FirstCtrl', function( $scope, $rootScope) {
$scope.firstName = 'Ganpat';
//$rootScope.$emit('firstName', $scope.firstName);
$rootScope.$broadcast('firstName:broadcast', $scope.firstName);
});
myApp.controller('SecondCtrl', function( $scope, $rootScope){
$rootScope.$on('firstName:broadcast', function(event,data){
$scope.firstName = data;
console.log(data);
});
});
</script>
<body>
<div ng-app="myApp">
<div ng-controller="FirstCtrl">
<input type="text" ng-model="firstName">
<br>Input is : <strong>{{firstName}}</strong>
</div>
<hr>
<div ng-controller="SecondCtrl">
Input should also be here: {{firstName}}
</div>
</div>
</body>
</html>
Code now compiles and runs properly. You can cut and past this into fiddler and run.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script>
var myApp = angular.module('myApp', []);
myApp.factory('UserService', function () {
var self = this;
var firstName = '';
self.SetFirstName = function (name) { firstName = name; }
self.GetFirstName = function () { return firstName; }
return self;
});
myApp.controller('FirstCtrl', ['$scope', 'UserService', function ($scope, UserService) {
UserService.SetFirstName("coolMan");
}]);
myApp.controller('SecondCtrl', ['$scope', 'UserService', function ($scope, UserService) {
$scope.firstNameTest = '';
$scope.service = UserService;
$scope.$watch('service.GetFirstName()', function (newVal) {
console.log("New Data", newVal)
$scope.firstNameTest = newVal;
});
}]);
</script>
<body>
<div ng-app="myApp">
<div ng-controller="FirstCtrl">
<input type="text" ng-model="firstName">
<br>
Input is : <strong>{{firstName}}</strong>
</div>
<hr>
<div ng-controller="SecondCtrl">
Input should also be here: {{firstNameTest}}
</div>
</div>
</body>
</html>
EDIT
Addressing OPS comment.
I know this method will work and it will give a correct result, but i
have studied the $rootscope and event $emiter and $broadcast will do
this trick, so if you know about that then please tell me, thank you
for your answer.
What you want to do is a bad idea. Your method forces a tighter coupling between controllers. By working on the rootscope you are forcing all controllers to rely on a certain Item being in rootscope. This is bad because controllers are not self contained modules.
By passing around a service you can decouple the controllers. Meaning that they can be used as view controllers, directive controllers, pretty much anything that requires an isolated module.
Also using a service you can now cache the result, perform centralized business logic on it, and encapsulate how you get the data. This cannot be done easily on the rootscope.
To sum it up, I will not show you a terrible way of doing what you want done. It is not good and will let other people whom look at this post use bad practices.

Function is not defined error in Angular.js

When I use this script:
<script>
function TestClick() {
alert("Test clic");
}
</script>
With this HTML code:
<div>
<input name="BtnAddNew" type="button" value="Load all OPCVM" onclick="TestClick()" />
</div>
It works.
But once I try to put everything inside a controller :
<head>
<meta name="viewport" content="width=device-width" />
<title>PetitsTests</title>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="~/Scripts/angular.js"></script>
<script>
var myApp= angular.module("myApp", []);
myApp.controller('OPCVMViewModel', function ($scope, $http) {
function TestClick() {
alert("test clic");
}
});
</script>
</head>
<body ng-app="myApp">
<div ng-controller="OPCVMViewModel">
<input name="BtnAddNew" type="button" value="Load all OPCVM" onclick="TestClick()" />
</div>
</body>
Then I get a "TestClick is not defined" error...
In your controller, try
$scope.TestClick = function(){ alert("test click"); };
And then in the button HTML:
type="button" ng-click="TestClick()"
In short, functions needs to be defined in scope. and use ng-click to call the function.
Example from the official docs:
var myApp = angular.module('myApp',[]);
myApp.controller('DoubleController', ['$scope', function($scope) {
$scope.double = function(value) { return value * 2; };
}]);
In short, you must attach whatever functions or properties you declare inside your controller to $scope in order to make them avaialbe to your template/view:
var app = angular.module("myApp", []);
app.controller('OPCVMViewModel', function ($scope, $http) {
function TestClick() {
alert('Test click');
}
$scope.TestClick = TestClick;
// or:
$scope.TestClick = function() {
alert('Test click');
};
});
Also, as JohnMoe has pointed out in the comments, there are other issues in your code.
First of, you should not use onclick, but ng-click. You can find the full list of ng directives here.
Moreover, the controller as syntax is the recommended way to go as from Angular 1.2, even though it will work without it.
Instead of writing something like:
app.controller('FooController', function ($scope) {
$scope.property = 'Foo';
});
You replace $scope for this, and now you don't need to inject $scope and have a nicer class-like looking controller:
app.controller('FooController', function () {
this.property = 'Foo';
});
Your templete will look like this:
<div ng-controller="FooController as vm">
{{ vm.property }}
</div>
If later on you decide to create a directive, it will look something like this:
app.controller('FooController', function () {
this.property = 'Foo';
});
app.directive('fooDirective', function () {
return {
restrict: 'E',
controller: 'FooController',
controllerAs: 'vm',
template: '{{ vm.property }}'
};
});
Also, you could use proper ES6 classes with a transpiler. Take a look at this if you are interested

Angular.js output value live on ng-click

I'm new to angular and little bit confused with it. So basically I created a simple button and i want to run function foo() whitch assigns variable var one = 1; to $scope and outputs it in <p>{{one}}<p> every time its clicked like in live typing but this seems not working. Please provide me a solution to this.
<html ng-app="app">
<!-- Body tag augmented with ngController directive -->
<body ng-controller="myController">
<input type="text" ng-model="name">
<p>{{name}}</p>
<p>{{one}}</p>
<button ng-click="foo()">1</button>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script src="controller.js"></script>
</body>
</html>
controller:
var app = angular.module('app',[]);
app.controller('myController', ['$scope',function($scope){
var one = 1;
$scope.name = name;
function foo(){
return $scope.one = one;
}
}]);
function foo() dont exist in $scope your controller "myController"
if you declaration:
$scope.foo = function(){}
in your controller, then this work for you
when you are calling controller function from the html, controller function should be scope. Other wise ng-click directive doesn't recognize the function.
same concept goes to binding variable to html. only scope variables can directly bind to html using curly brackets. so inside foo function var one should assign to scope.one in order to display it in the html.
angular.module("app",[])
.controller("ctrl",function($scope){
var one = 1;
$scope.name = name;
$scope.foo = function(){
$scope.one = one;
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<input type="text" ng-model="name">
<p>{{name}}</p>
<p>{{one}}</p>
<button ng-click="foo()">1</button>
</div>

Calling anonymous method recursively in angular controller method

I want to send ajax requests at regular intervals from the angular controller method. for that i have written code like below.
var mainApp = angular.module('myapp',[]);
mainApp.controller('controller', function($scope,$http,$window,$timeout) {
$('#radioBtn a').on('click', function(){
$http({
method:,
url:,
params:{parameters}
}).then(function(success){
},function(error){
});
$timeout(function(){
//how to call the anonymous function passed to $('#radioBtn a').on() here.
},30000);
});
I am not getting how to call the anonymous method from timeout function. Using this() is failing.
First off: Don't bind to element clicks like that, use the ng-click directive - in fact, just don't even load jQuery in your application, in 99% cases you're better off without it.
Second: Use angular's $interval service. Check the code sample below.
angular.module('app', [])
.controller('ctrl', function($scope, $interval) {
$scope.numbers = [];
$scope.startInterval = function() {
$scope.interval = $interval(function() {
$scope.numbers.push($scope.numbers.length);
}, 1000)
}
})
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js#1.6.0" data-semver="1.6.0" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="app" ng-controller="ctrl">
<button ng-if="!interval" ng-click="startInterval()">Start polling</button>
<div ng-repeat="number in numbers">
{{number}}
</div>
</body>
</html>
try this way.
var mainApp = angular.module('myapp',[]);
mainApp.controller('controller', function($scope,$http,$window,$interval) {
$('#radioBtn a').on('click', function(){
$interval(function(){
$http({
method:,
url:,
params:{parameters}
}).then(function(success){
},function(error){
});
},30000);
});

Ways to declare Function in AngularJS Controller (controllerAs approach)

I use controller as approach instead of $scope. I have some problems with method calling from HTML. So, the question is that, how many ways exist in declare and call functions in this approach.
first: (If I want to do s.th. at first)
var vm= this ;
vm.dataOne=[];
function funcOne() {
myService.serviceFunc()
.then(function (response) {
vm.dataOne= response.data;
});
};
function activate() {
funcOne();
}
activate();
second: (If I want to initialize a variable based on a function returned value )
vm.dataTwo = function () {
doSomeThing();
}
Is there any way, too?
How should define a function in controller
which will be called from HTML, as
ng-click = "ctrl.dataTwo()";
Functions the way you've defined are private:
function functionOne() {
}; // Just function body, no need of semicolon
These are known as function declarations. Currently, they are only accessible within your controller.
To be able to call them, attach them to the controller so they become controller variables:
vm.functionOne = functionOne;
An advantage of this approach is that you can define functions after actually calling them, as opposed to how you do with $scope or $this. They are recognized via hoisting, and called.
About your initializing a returned value from a function, just call it:
vm.someVariable = someFunction();
Some references:
var functionName = function() {} vs function functionName() {}
Private Members in JavaScript
Angular Function Declarations, Function Expressions, and Readable Code
Angular Style Guide
First way using ng-controller="cntrl as vm" syntax:
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script>
angular.module('MyApp', [])
.controller('MyCntrl', function($scope) {
var vm = this;
vm.name = 'Custom Directive';
});
</script>
<body>
<div ng-app="MyApp" ng-controller="MyCntrl as vm">
{{vm.name}}
</div>
</body>
</html>
Second way using controllerAs as one of the attribute of directive:
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script>
angular.module('MyApp', [])
.directive('customDir', function() {
return {
restrict: 'EA',
template: '<div>{{vm.name}}</div>',
controller: function(){
var vm = this;
vm.name = 'Custom Directive';
},
controllerAs: 'vm'
}
});
</script>
<body>
<div ng-app="MyApp">
<div custom-dir></div>
</div>
</body>
</html>
Way to calling a function with "controller as" syntax which is defined in controller but called in html:
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script>
angular.module('MyApp', [])
.controller('MyCntrl', function($scope) {
var vm = this;
vm.name = 'Custom Directive';
vm.someFunction = function() {
vm.name = 'Button is Clicked!!!';
};
});
</script>
<body>
<div ng-app="MyApp" ng-controller="MyCntrl as vm">
{{vm.name}}
<input type='button' ng-click="vm.someFunction()" value="Click" />
</div>
</body>
</html>
Other way, use function as constructor and add functionality to prototype
function Ctrl($window) {
this.$window = $window;
}
Ctrl.inject = ['$window']
Ctrl.prototype.click = function() {
this.$window.alert('clicked')
}
angular.module('app', [])
.controller('ctrl', Ctrl)
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='app' ng-controller='ctrl as c'>
<button ng-click='c.click()'>Click me!</button>
</div>

Categories

Resources