I want get HttpContext.Current.Request.AnonymousID of users in Razor and then send it to an action in a controller in this way:
<script>
app.controller('loginController', function ($http, $scope, $location, $rootScope) {
$scope.login = function () {
//Send Anonymous to UserLogin action
$http.post("/Accounts/UserLogin?anonymous="+AnonymousId, $scope.model).success(function (response) {
$scope.message = response;
window.location = '/';
$rootScope.ShowSpinner = false;
});
}
});
</script>
Is there any way to do this?
In razor you can have something like
#{
// Just to make my expression smaller
var anonymousId = HttpContext.Current.Request.AnonymousID;
}
<script>
angular.module("someModule").value("anonymousId", "#anonymousId" );
</script>
Note injecting Razor is just normal. If it fails, try wrapping in (), like "#(anonymousId)". The only trick is that I just wrapped the value in quotes so that it's a string in JavaScript.
Then you can inject this value into your Angular controller:
<script>
app.controller('loginController',
function ($http, $scope, $location, $rootScope, anonymousId) {
$scope.login = function () {
//Send Anonymous to UserLogin action
$http.post("/Accounts/UserLogin?anonymous="+anonymousId, $scope.model)
.success(function (response) {
...
});
}
});
</script>
Of course you can also write it directly in the controller as well...
....
$http.post("/Accounts/UserLogin?anonymous="
+ "#(HttpContext.Current.Request.AnonymousID)", $scope.model).
....
Related
How can I get the username from index.html?
index.html
{{username}}
index controller:
app.controller('index',function($scope,$rootScope,mainService){
$scope.getUsername = funciton(){
mainService.getUsername().then{
function successCallback(response){
$rootScope.username = response.data.username;
}
}
}
})
iframe.html
{{user}}
iframe controller
app.controller('iframe',function($scope,$rootScope){
$scope.user = $rootScope.username
})
but {{user}} show nothing
Also, I tried to post the message by Service like dataService.username result is the same.
Use $rootScope.$broadcast to raise an event, first paramter for the event name and an optional second parameter to pass an argument.
app.controller('IndexController', function ($scope, $rootScope, MainService) {
$scope.getUsername = function() {
MainService.getUsername().then(function (response) {
$rootScope.$broadcast('username-fetched', { username: response.data.username });
});
};
});
Then catch the event on the other controller by using $scope.$on.
app.controller('IframeController', function ($scope) {
$scope.$on('username-fetched', function (event, data) {
$scope.user = data.username;
});
});
I have a view for SidebarController like below -
<a ng-click="reachMe($event);$event.preventDefault()" ng-href="#/app/hello">
Before going to the link I want to call reachMe() to check some changes on page and need to show an alert if any changes made
function SidebarController($rootScope, $scope, $state, $location, SidebarLoader){
$scope.reachMe = function(event){
//here I want to call function isPageChanged() from StaticPageController
//something like this
// if StaticPageController.isPageChanged() return true
// then show alert
// else
// $location.url($href)
}
}
Update 1 :
Not sure about this, But give it a try.
<div ng-app="testApp" ng-controller="ControllerOne">
<button ng-click="methodA();"> Call Another Controller</button>
</div>
<script>
var app = angular.module('testApp', []);
app.controller('ControllerOne', function($scope, $rootScope) {
$scope.reachMe = function() {
var arrayData = [1,2,3];
$rootScope.$emit('callEvent', arrayData);
if($rootScope.isChanged){
// Show Alert
}else{
//Go to route
}
}
});
app.controller('ControllerTwo', function($scope, $rootScope,$state) {
$scope.checkSomethingChanged = function() {
alert("Hello");
$rootScope.isChanged = true;
}
$rootScope.$on('callEvent', function(event, data) {
console.log(data);
$scope.checkSomethingChanged();
});
});
Following method worked for me perfectly :
<div ng-app="testApp" ng-controller="ControllerOne">
<button ng-click="methodA();"> Call Another Controller</button>
</div>
<script>
var app = angular.module('testApp', []);
app.controller('ControllerOne', function($scope, $rootScope) {
$scope.methodA = function() {
var arrayData = [1,2,3];
$rootScope.$emit('callEvent', arrayData);
}
});
app.controller('ControllerTwo', function($scope, $rootScope) {
$scope.reachMe = function() {
alert("Hello");
}
$rootScope.$on('callEvent', function(event, data) {
console.log(data);
$scope.reachMe();
});
});
</script>
A controller is not the right concept for sharing functionality. Use a Factory or Service for that.
var logicFactory = function () {
return {
methodA: function () {
},
methodB: function()
{
}
};
}
You can then inject that factory into each controller where it is needed like:
var ControllerA = function ($scope,logicFactory) {
$scope.logic = logicFactory;
}
ControllerA.$inject = ['$scope', 'logicFactory'];
Another option is to use the broadcast/emit Patern. But I would use that only where really necessary:
Usage of $broadcast(), $emit() And $on() in AngularJS
I am trying to set communication between two angular controllers (service is not an option). and I am failing desperately.
here is some of my code...
i tried using both $emit and $broadcast
invoiceApp.controller('masterReportConrtoller', ['$scope', '$location', 'authService', 'usSpinnerService', 'dateService', 'settingsService','$rootScope',
function ($scope, $location, authService, usSpinnerService, dateService, settingsService, $rootScope )
////Is User Valid
////
//$rootScope.$on("masterReportConrtoller", function () {
// $scope.parentmethod();
// });
//$scope.parentmethod = function () {
// //
$scope.masterReportConrtoller.getUserDetails = function () {
debugger;
settingsService.getUserDetails().then(function (response) {
var loginData = {
userName: response.d.user.Email,
password: response.d.user.UserPassword
};
authService.login(loginData).then(function (response) {
debugger;
$scope.Limit = response.d.organization.Limit;
});
$scope.Limit = response.d.organization.Limit;
$scope.DocumentUsage = response.d.organization.DocumentUsage;
$scope.ExpirationDate = $scope.DateConvertfromJson(response.d.organization.ExpirationDate);
var fullDate = new Date();
if (fullDate <= $scope.ExpirationDate) {
$scope.ISvalidUser = false;
$rootScope.$broadcast('masterReportConrtoller', false);
}
else {
$rootScope.$broadcast('masterReportConrtoller', true);
}
});
}
}]);
invoiceApp.controller('InvoiceController', ['$scope', '$location', '$cookieStore', 'documentService', 'dialogs', 'usSpinnerService', 'settingsService', 'associatedEmailsService', '$rootScope',
function ($scope, $location, $cookieStore, documentService, dialogs, usSpinnerService, settingsService, associatedEmailsService, $rootScope) {
$rootScope.$on('masterReportConrtoller');}
Based on your parent - child controller relationship, you can use $scope.$broadcast and $scope.$on in your code.
Try something like this:
//masterReportConrtoller
$scope.$broadcast("myCustomEvent", { isValidUser: false });
//InvoiceController
$scope.$on("myCustomEvent" , function(event, data){
//do something with data
});
Please note that this will work if masterReportConrtoller is the parent controller and InvoiceController is the child controller. If this is not the case, then use $rootScope.$broadcast and $rootScope.$on.
You can find more details here.
You can use $localStorage , $stateParams or $cookies or even ... I generally prefer $stateParams to send values and object to states and controller.
$state.go('state2', { someParam : 'broken magic' });
read file using $stateParams from controller . Details can be found here
I'm trying to pass data from one controller to another using a service, however no matter what I'm trying it always returns 'undefined' on the second controller. Here is my service :
app.service('myService', ['$rootScope', '$http', function ($rootScope, $http) {
var savedData = {}
this.setData = function (data) {
savedData = data;
console.log('Data saved !', savedData);
}
this.getData = function get() {
console.log('Data used !', savedData);
return this.savedData;
}
}]);
Here is controller1 :
.controller('HomeCtrl', ['$scope','$location','$firebaseSimpleLogin','myService','$cookies','$window', function($scope,$location, $firebaseSimpleLogin, myService, $cookies, $window) {
loginObj.$login('password', {
email: username,
password: password
})
.then(function(user) {
// Success callback
console.log('Authentication successful');
myService.setData(user);
console.log('myservice:', myService.getData()); // works fine
}]);
And then controller2:
// Dashboard controller
.controller('DashboardCtrl', ['$scope','$firebaseSimpleLogin','myService',function($scope,$firebaseSimpleLogin, $location, myService) {
console.log('myservice:', myService.getData()); //returns undefined
}]);
That is simple code, unfortunately I've been struggling for a few hours now, any suggestion ? Thanks.
Created a fiddle here:
http://jsfiddle.net/frishi/8yn3nhfw/16
To isolate the problem, can you remove the dependencies from the definition for myService and see if that makes it work? Look at the console after you load the fiddle.
var app = angular.module('app', [])
.service('myService', function(){
this.getData = function(){
return "got Data";
}
})
I assume the issue is that you are returning this.savedData in the service. Try returning savedData.
this behaves different in Javascript than in other languages.
I'm not able to get the data binding between controller and service working.
I have a controller and a factory which makes an HTTP call. I would like to be able to call the factory method from other services and see the controller attributes get updated. I tried different options but none of them seem to be working. Any ideas would be greatly appreciated.
Please see the code here:
http://plnkr.co/edit/d3c16z?p=preview
Here is the javascript code.
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
});
app.controller('EventDetailCtrl', ['$http', 'EventDetailSvc', '$scope',
function ($http, EventDetailSvc, $scope) {
this.event = EventDetailSvc.event;
EventDetailSvc.getEvent();
console.log(self.event);
$scope.$watch(angular.bind(this, function () {
console.log('under watch');
console.log(this.event);
return this.event;
}), function (newVal, oldVal) {
console.log('under watch2');
console.log(newVal);
this.event = newVal;
});
}])
.factory('EventDetailSvc', ['$http', function ($http) {
var event = {};
var factory = {};
factory.getEvent = function() {
$http.get('http://ip.jsontest.com')
.then(function (response) {
this.event = response.data;
console.log('http successful');
console.log(this.event);
return this.event;
}, function (errResponse) {
console.error("error while retrieving event");
})
};
factory.event = event;
return factory;
}]);
It seems to me that you have nested the event object inside of a factory object. You should be returning event directly instead wrapping it with factory. As it stands now you would need to call EventDetailSvc.factory.event to access your object.