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;
});
});
Related
In the below, I have a sidenav and a main content section. I am trying to call the sidenav function from the main controller so the number updtes in the sidenav. What am I doing wrong here?
This is my view.
<div>Teams {{ teams.length }} </div>
This is my sidebar controller:
angular.module('myApp').controller('leftNav', function($scope, myFactory) {
myFactory.getTeams().then(function(res) {
$scope.teams = res.data;
})
This is my factory
angular.module('myApp').factory('myFactory', function($http) {
return {
getTeams : function() {
return $http.get('/teams').then(function(res) {
return res;
});
}
};
});
This is a complete different controller:
angular.module('myApp').controller('main', function($scope,$http, myFactory) {
$http.post(...blablabl..).then(function() {
// What can i call here to update the sidenav above?
});
});
You can utilise $controller service to call your leftNav controller from your main controller like below
angular.module('myApp').controller('main', function($scope,$http, myFactory,$controller) {
$http.post(...blablabl..).then(function() {
var leftCTRL= $controller('leftNav', { $scope: $scope.$new() });
});
});
you can try like so :
angular.module('myApp').controller('leftNav', function($scope, myFactory) {
myFactory.getTeams().then(function(res) {
this.teams = res.data;
})
angular.module('myApp').controller('main', function($scope,$http, $controller) {
var leftNav= $controller('leftNav');
$http.post(...blablabl..).then(function(res) {
leftNav.teams = res.data;
});
});
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).
....
I'm using Facebook connect to login my clients.
I want to know if the user is logged in or not.
For that i use a service that checks the user's status.
My Service:
angular.module('angularFacebbokApp')
.service('myService', function myService($q, Facebook) {
return {
getFacebookStatus: function() {
var deferral = $q.defer();
deferral.resolve(Facebook.getLoginStatus(function(response) {
console.log(response);
status: response.status;
}));
return deferral.promise;
}
}
});
I use a promise to get the results and then i use the $q.when() to do additional stuff.
angular.module('angularFacebbokApp')
.controller('MainCtrl', function ($scope, $q, myService) {
console.log(myService);
$q.when(myService.getFacebookStatus())
.then(function(results) {
$scope.test = results.status;
});
});
My problem is that i need to use the $q.when in every controller.
Is there a way to get around it? So i can just inject the status to the controller?
I understand i can use the resolve if i use routes, but i don't find it the best solution.
There is no need to use $q.defer() and $q.when() at all, since the Facebook.getLoginStatus() already return a promise.
Your service could be simpified like this:
.service('myService', function myService(Facebook) {
return {
getFacebookStatus: function() {
return Facebook.getLoginStatus();
}
}
});
And in your controller:
.controller('MainCtrl', function ($scope, myService) {
myService.getFacebookStatus().then(function(results) {
$scope.test = results.status;
});
});
Hope this helps.
As services in angularjs are singleton you can create new var status to cache facebook response. After that before you make new call to Facebook from your controller you can check if user is logged in or not checking myService.status
SERVICE
angular.module('angularFacebbokApp')
.service('myService', function myService($q, Facebook) {
var _status = {};
function _getFacebookStatus() {
var deferral = $q.defer();
deferral.resolve(Facebook.getLoginStatus(function(response) {
console.log(response);
_status = response.status;
}));
return deferral.promise;
}
return {
status: _status,
getFacebookStatus: _getFacebookStatus
}
});
CONTROLLER
angular.module('angularFacebbokApp')
.controller('MainCtrl', function ($scope, $q, myService) {
console.log(myService);
//not sure how do exactly check if user is logged
if (!myService.status.islogged )
{
$q.when(myService.getFacebookStatus())
.then(function(results) {
$scope.test = results.status;
});
}
//user is logged in
else
{
$scope.test = myService.status;
}
});
Hi I have got one question.
I have got one object as following in my Factory
User: {
EmailAddress: ""
}
whenever i make http call I want to update that User.EmailAddress whith returned value. What is the best way of doing it in within the factory? so that at controller level I can just bind my $scope.Email to factory variable. This is what I am doing right now
GetLogOnModel: function () {
if ($location.path().indexOf("login") == 1) {
var promise = $http.get(config.headers.url + "LogOn").then(function (response) {
// The return value gets picked up by the then in the controller.
User.EmailAddress=response.data.Email;
return response.data
});
return promise;
// Return the promise to the controller
}
}
And in Controller
AccountFactory.GetLogOnModel().then(function (data) {
$scope.logOnModel = data;
}, function (err) {
console.log(err.reason);
alert(err.reason);
});
Primitive types (such as strings) are not bound by reference. So you can't bind a scope property to EmailAddress directly and expect it to get automatically updated.
Objects on the other hand are bound by reference, so you could do something like this:
app.factory('AccountFactory', function (...) {
...
var User = {
...
EmailAddress: null
};
function getLogOnModel() {
$http.get(...).then(function (response) {
User.EmailAddress = response.data.Email;
});
}
// Init model (or leave it for the controller to init it)
getLogOnModel();
return {
...
User: User,
getLogOnModel: getLogOnModel
};
});
app.controller('someCtrl', function (..., AccountFactory) {
$scope.user = AccountFactory.User;
// Now you can reference `$scope.user.EmailAddress`
// and it will be kept in sync with `AccountFactory.User.EmailAddress`
});
It should be pretty straight forward. Either you bind the instance of the service or just the email property to the $scope.
Here I'm just updating the email after 5 secs.
myApp.factory('myService', function($http, $timeout) {
return {
email: 'foo#bar.com',
updateEmail: function() {
var self = this;
$timeout(function() {
$http.get('/echo/json/').success(function() {
self.email = 'bar#foo.com';
});
}, 5000);
}
};
});
1st Method:
Bind the entire service on the scope as:
function MyCtrl($scope, myService) {
$scope.myService = myService;
myService.updateEmail();
});
<div ng-controller="MyCtrl">
myService: {{myService.email}}!
</div>
2nd Method
Just create a custom $watch for email updates:
function MyCtrl($scope, myService) {
$scope.email = myService.email;
myService.updateEmail();
$scope.$watch(function() { return myService.email; }, function(newVal, oldVal) {
$scope.email = newVal;
});
}
<div ng-controller="MyCtrl">
$scope: {{email}}
</div>
I would recommend the first method because it requires only one $watch to update the DOM i.e. for {{myService.email}} whereas the second method requires two $watches i.e. one to update the $scoped model ($scope.$watch) and other to update the DOM as {{email}}.
Demo: http://jsfiddle.net/HB7LU/3015/
I am trying to configure my first tidbits of the AngularJs for a trivial stuff, but unfortunately unsuccessful at it after considerable amount of time.
My Premise:
Users select one of the options from a dropdown and have an appropriate template loaded into a div below the select. I have set up the service, a custom directive (by following the ans by #Josh David Miller on this post, and a controller in place. The ajax call in service is working fine except that the params that I pass to the server is hardcoded. I want this to be the 'key' from the dropdown selected by user. At the moment I am failing to have this code passed to the service.
My configuration:
var firstModule = angular.module('myNgApp', []);
// service that will request a server for a template
firstModule.factory( 'katTplLoadingService', function ($http) {
return function() {
$http.get("${createLink(controller:'kats', action:'loadBreedInfo')}", {params:{'b1'}}
).success(function(template, status, headers, config){
return template
})
};
});
firstModule.controller('KatController', function($scope, katTplLoadingService) {
$scope.breed = {code:''}
// here I am unsuccessfully trying to set the user selected code to a var in service,
//var objService = new katTplLoadingService();
//objService.breedCode({code: $scope.breed.code});
$scope.loadBreedData = function(){
$scope.template = katTplLoadingService();
}
});
firstModule.directive('showBreed', function ($compile) {
return {
scope: true,
link: function (scope, element, attrs) {
var el;
attrs.$observe( 'template', function (tpl) {
if (angular.isDefined(tpl)) {
el = $compile(tpl)(scope);
element.html("");
element.append(el);
}
});
}
};
})
and the HTML setup is
<form ng-controller="KatController">
<select name="catBreeds" from="${breedList}" ng-change="loadBreedData()"
ng-model="breed.code" />
<div>
<div show-breed template="{{template}}"></div>
</div>
</form>
I need the currently hardcoded value 'b1' in the $http ajax call to be the value in $scope.breed.code.
Your ajax request is async while your controller behaves as if the request were sync.
I assume that the get request has everything it needs to perform right.
First pass a callback to your service (note the usage of fn):
firstModule.factory( 'katTplLoadingService', function ($http) {
return {
fn: function(code, callback) { //note the callback argument
$http.get("${createLink(controller:'kats', action:'loadBreedInfo')}",
params:{code: code}}) //place your code argument here
.success(function (template, status, headers, config) {
callback(template); //pass the result to your callback
});
};
};
});
In your controller:
$scope.loadBreedData = function() {
katTplLoadingService.fn($scope.breed.code, function(tmpl) { //note the tmpl argument
$scope.template = tmpl;
});
}
Doing so your code is handling now your async get request.
I didn't test it, but it must be doing the job.
I think you defined the factory not in right way. Try this one:
firstModule.factory('katTplLoadingService', ['$resource', '$q', function ($resource, $q) {
var factory = {
query: function (selectedSubject) {
$http.get("${createLink(controller:'kats', action:'loadBreedInfo')}", {
params: {
'b1'
}
}).success(function (template, status, headers, config) {
return template;
})
}
}
return factory;
}]);
firstModule.controller('KatController', function($scope, katTplLoadingService) {
$scope.breed = {code:''}
$scope.loadBreedData = function(){
$scope.template = katTplLoadingService.query({code: $scope.breed.code});
}
});