pass variable inside same controller from ng-click angular JS [duplicate] - angularjs

This question already has answers here:
Pass value in-between angular JS controller and services
(3 answers)
Closed 7 years ago.
I want to get the variable value which has been assigned inside ng-click function
mainApp.controller('setSearchController',function($scope) {
$scope.getQuery = function(userq) //ng-click function
{
$scope.userq=userq;
};
alert($scope.userq); // showing Undefined even after the click is made
// Once clicked I want to use **userq** value to make one $https call
// apart from services,How to use userq here outside getQuery scope
});
before using ng-click , its ok to get undefined value but what I am trying to do is to use the same controller for another view , which will be rendered after the ng-click happens
.when('/search', {
templateUrl: "../static/views/seachResult.html",
controller: "setSearchController"
})
so I want to fetch some searched data in searchResult.html view after $https call

Take a look at my answer here:
Pass value in-between angular JS controller and services
It is the same question, I have solved your problem with event listeners using $on and $emit

HTML:
<div ng-app="myApp" ng-controller="myCtrl">
<button ng-click="getQuery('myVal')">Test</button>
<button ng-click="consoleIt(myVal)">Console</button>
</div>
Controller:
angular.module('myApp', [])
.controller('myCtrl', ['$scope', function($scope) {
$scope.getQuery = function(a){
$scope[a] = a;
}
$scope.consoleIt = function(a){
console.log(a);
}
}]);
The getQuery function creates a new property on your scope. The property's name is equal to what is passed (string) as agrument to the function. consoleIt simply console logs its agrument. myVal is undefined until you click the test button. You can also pass a variable (instead of string) to getQuery, in this case just remove the quotes from inside of parenthesis.

Move alert inside statement function getQuery.
mainApp.controller('setSearchController', function($scope) {
$scope.userq = null;
$scope.getQuery = function(userq) //ng-click function
{
$scope.userq=userq;
alert($scope.userq);
};
});
or this solution
mainApp.controller('setSearchController', ['$scope', '$window', setSearchController]);
function setSearchController ($scope, $window) {
$scope.userq = null;
$scope.getQuery = function(userq) //ng-click function
{
$scope.userq=userq;
$window.alert($scope.userq);
};
}

Related

What is the difference between two scopes in the same controller (one from a service) to a directive?

I've got the below controller with two scope variables and only one passes through to my directive?
.controller('newsController', ['$scope', 'gasPrices',
function($scope, gasPrices) {
gasPrices.success(function(data) {
$scope.gasFeed = data.series[0];
});
$scope.myData02 = [2.095,2.079,2.036,1.988,1.882,1.817,1.767,1.747];
}])
;
I've got a directive that accepts one scope but not the other?
This works
<line-chart chart-data="myData02"></line-chart>
This doesn't
<line-chart chart-data="gasFeed"></line-chart>
Do you know why?
You have to delay instantiating the directive until the data from your async service is available. Something like:
<line-chart ng-if="gasFeed" chart-data="gasFeed"></line-chart>
This should not instantiate the directive until the gasFeed scope property has data.
Try this:
.controller('newsController', ['$scope', 'gasPrices',
function($scope, gasPrices) {
//Create a object that will be pass in the directive, then when this variable
//it's loaded, the value in the directive (if the scope of the directive uses the '=' binding) will be updated
$scope.gasFeed = {};
gasPrices.success(function(data) {
$scope.gasFeed = data.series[0];
});
$scope.myData02 = [2.095,2.079,2.036,1.988,1.882,1.817,1.767,1.747];
}]);
Yes.
Here, in your example you can access gasFeed scope only when when there is a success callback from the service. Hence, till then myData02 scope will be loaded.
If you want to access both. Then try this :
.controller('newsController', ['$scope', 'gasPrices',
function($scope, gasPrices) {
gasPrices.success(function(data) {
$scope.gasFeed = data.series[0];
$scope.myData02 = [2.095,2.079,2.036,1.988,1.882,1.817,1.767,1.747];
});
}]);

How to call a function from another controller in AngularJS? [duplicate]

This question already has answers here:
Can one AngularJS controller call another?
(14 answers)
How do I inject a controller into another controller in AngularJS
(7 answers)
Closed 7 years ago.
I need to call a function in another controller in AngularJS. How can I do this?
Code:
app.controller('One', ['$scope',
function($scope) {
$scope.parentmethod = function() {
// task
}
}
]);
app.controller('two', ['$scope',
function($scope) {
$scope.childmethod = function() {
// Here i want to call parentmethod of One controller
}
}
]);
Communication between controllers is done though $emit + $on / $broadcast + $on methods.
So in your case you want to call a method of Controller "One" inside Controller "Two", the correct way to do this is:
app.controller('One', ['$scope', '$rootScope'
function($scope) {
$rootScope.$on("CallParentMethod", function(){
$scope.parentmethod();
});
$scope.parentmethod = function() {
// task
}
}
]);
app.controller('two', ['$scope', '$rootScope'
function($scope) {
$scope.childmethod = function() {
$rootScope.$emit("CallParentMethod", {});
}
}
]);
While $rootScope.$emit is called, you can send any data as second parameter.
I wouldn't use function from one controller into another. A better approach would be to move the common function to a service and then inject the service in both controllers.
You may use events to provide your data. Code like that:
app.controller('One', ['$scope', function ($scope) {
$scope.parentmethod=function(){
$scope.$emit('one', res);// res - your data
}
}]);
app.controller('two', ['$scope', function ($scope) {
$scope.$on('updateMiniBasket', function (event, data) {
...
});
}]);
If the two controller is nested in One controller.
Then you can simply call:
$scope.parentmethod();
Angular will search for parentmethod function starting with current scope and up until it will reach the rootScope.
The best approach for you to communicate between the two controllers is to use events.
See the scope documentation
In this check out $on, $broadcast and $emit.
If you would like to execute the parent controller's parentmethod function inside a child controller, call it:
$scope.$parent.parentmethod();
You can try it over here

Calling a scope function in different controller

I have a function defined in a controller , I want to call it in another controller.
I tried to attach it to the $rootscope so I can see in the other controller , but I couldn't .
Is there a way for calling it, without attaching it to the $rootscope?
As far as I know in AngularJS you can share info between controllers in 3 ways:
1 - Creating a Service.
2 - Creating a function linked to $rootScope.
3 - Using events ($broadcast and $on). I use a lot this method in my projects.
I think your problem is that you don't instantiate the controllers in
the proper order or one of them is never instantiated, therefore the
function you want to link to $rootScope in that controller or the broadcast event never fires.
E.G If you want to call a function linked to $rootScope in the 2 controller from the
first one, it is impossible because the 2 controller is instantiated after the first one.
This case happens when you make calls on application runtime.
I will implement your method with some changes:
HTML:
<div ng-controller="MyCtrl_1"></div>
<div ng-controller="MyCtrl_2">
<button ng-click="send()">Send Mess</button>
</div>
JS:
var myApp = angular.module('myApp',[]);
function MyCtrl_1($scope, $rootScope) {
$scope.$on('RenderPage', function (event, PageId) {
$scope.RenderPage = PageId;
alert($scope.RenderPage);
});
};
function MyCtrl_2($scope, $rootScope) {
$scope.MasterPageId = 10;
$scope.send = function(){
$rootScope.$broadcast('RenderPage', $scope.MasterPageId);
}
};
Use carefully $broadcast and $emit, because has different behavior each one.
Try here: http://jsfiddle.net/1ypkb4s9/
Otherwise, post your error.
Simply wrap them with a "father controller":
HTML:
<div ng-app="myApp" ng-controller="myOuterCtrl">
<div ng-controller="myInnerCtrl1">
<button ng-click="outerClick()">Outer Click</button>
</div>
<div ng-controller="myInnerCtrl2">
<button ng-click="innerTwoClick()">Inner Click</button>
</div>
</div>
JS:
angular.module('myApp', []).
controller('myOuterCtrl', function ($scope) {
$scope.outerClick = function () {
console.log('outer click');
}
}).
controller('myInnerCtrl1', function ($scope) {
// nothing here!!
}).
controller('myInnerCtrl2', function ($scope) {
$scope.innerTwoClick = function () {
console.log('inner two click');
}
});
JSFIDDLE.
if you want to use the same function in two or more controllers you might need a service.
or use events
function firstCtrl($scope)
{
$scope.$broadcast('someEvent', [1,2,3]);
}
function secondCtrl($scope)
{
$scope.$on('someEvent', function(event, mass) { console.log(mass); });
}

How to retain the variable's value of JSP using AngularJS

I am new to AngularJS. I am trying learn to pass the value of a variable to the angularJS.
But for some unknown reason, I am not being able to do.
Below is the .jsp page which I think is correct:
<body >
<div ng-controller="customersController">
<label>Value</label>
<input type="text" ng-model=something></input>
<button ng-click="punchIt()">click me!</button>
<br>Obtained value : {{ value }}
</div>
</body>
In the respective .js page, value passed from .jsp file is not getting retained.The first alert function should return assumed : something's value,but it is returning assumed : undefined.
Below is the .js file:
var myApp = angular.module("getInfo", []);
myApp.controller("customersController", function($scope, $http){
$scope.punchIt = function ($scope, $http) {
var data = {Value: $scope.something};
alert("assumed : "+ $scope.something);
$http.post("http://localhost:8082/HelloWorldWS/services/HelloWorldImpl",data)
.success(function (data, status, header) {
alert("in success " + data);
$scope.value = data;
}).error(function (data) {
alert("in error method " + status);
$scope.value = "error "+ data;
});
};
});
Please suggest some way out.
Thanks.
You are expecting two variables ($scope and $http) in your punchIt() function declaration but not passing these when you call it on button click. Thus inside your punchit() function, both $scope and $http variables would be initialized to nothing (read undefined).
You actually dont need to pass these parameters to your function. Your controller already has these services injected in it via your controller declaration.
Also declare/initialize the name variable in your controller. Else, if you do not enter anything in the input field and try to access it in your $scope, you will retrive it as undefined.
Your code changes would look as below:
myApp.controller("customersController", function($scope, $http){
$scope.name=null;
//OR $scope.name='';
$scope.punchIt = function () {
...
}
}

Angular JS: attribute not influenced by $scope...?

Angular newbie here.
I have the following div:
<div id="mainfr" data-curpos="dy[ {{curPosObj.dy}} ]" ...>blah blah </div>
And in my controller I have:
var nxtest = angular.module('nxtest', []);
var appController = nxtest.controller('AppCtrl', ['$scope', function ($scope) {
$scope.curPosObj = { dir: "down", dy:5 };
$scope.clr = window.setTimeout(function(){ $scope.curPosObj.dy = 777;
window.clearTimeout($scope.clr); }, 5000); //see if the attr responds to a random change
}])
In firebug, inspecting the scope object shows that it is indeed modified. I want to understand why the bound attribute {{curPosObj.dy}} is not 'bound' and the view does not respond to the changing values? Thanks very much in advance.
Update: added link to plunker as suggested - the red text never changes:
http://plnkr.co/edit/HJxEpgR8VepxuT47zJDJ?p=preview
Update 2: OK so there may be a separate issue here - the red text is in a pseudo element whose contrent attribute depends on the main divs attribute... and I'm not calling setAttribute anywhere... but regardless: in firebug, the 'data-curpos' attribute itself is NOT updating, never mind the pseudo elem that depends on it...
That's because angular doesn't tracking scope changes out of the dygest cycle and window.setTimeout that case. You should use the $timeout service instead of window.setTimeout or put code which chenge scope into $scope.$apply call
angularjs API reference - $timeout service
angularjs API reference - scope guide
try this:
var nxtest = angular.module('nxtest', []);
var appController = nxtest.controller('AppCtrl', ['$scope', '$timeout',
function($scope, $timeout) {
$scope.curPosObj = {
dir: "down",
dy: 5
};
$scope.clrPromise = $timeout(function() {
$scope.curPosObj.dy = 777;
}, 5000); //see if the attr responds to a random change
}
])

Resources