Access Angular $scope in plain javascript - angularjs

I have a Controller which has something like this...
angular.module('kZoneApp').controller('DemandController', ['$http', '$scope', '$rootScope', 'dataFactory', '$window', '$routeParams','$sce', function ($http, $scope,$rootScope, dataFactory, $window, $routeParams,$sce) {
$scope.channel = $routeParams.channel;
now within my page.html, I want to do the following....
<script>
YoutubeVideoPlayer.openVideo('{{channel}}');
</script>
please note, I am using Routes, and page.html is loaded into my ng-view Via a Route.
<div id="myView" class="reveal-animation" ng-view></div>
I tried below code, but it returns undefined....
$().ready(function () {
var channel = angular.element("#myView").scope().channel
YoutubeVideoPlayer.openVideo(channel);
})
How can I get the value of Channel within my Template View?
Update
below works...but I am sure there has to be a cleaner solution
setTimeout(function () {
alert(angular.element("#myView").scope().channel)
}, 500);

A workaround solution should be creating a variable before your Angular.module definition.
var scopeInAngular = null;
and inside controller assign controller to your variable.
scopeInAngular = $scope;
then if you manipulate anything inside angular view use
scopeInAngular.$apply();

Related

How to execute code once in the beginning of an Angular app

I have a situation where I need to have a piece of code execute only once at the start of the angular app. My app searches for a beacon using the cordova-plugin and if it finds one, the app is redirected to another state otherwise it stays on the home/splash state.
Currently I have this code running in the "home" controller and it is working but I was hoping for a more elegant solution. I am controlling the state change using a simple if/else statement and a variable on the $scope.
Here's my controller:
homeCtrl.$inject = ['$scope', '$state', '$rootScope', '$ionicPlatform', '$cordovaBeacon'];
function homeCtrl($scope, $state, $rootScope, $ionicPlatform, $cordovaBeacon) {
$scope.skip = false;
$ionicPlatform.ready(function() {
$cordovaBeacon.requestWhenInUseAuthorization();
$rootScope.$on("$cordovaBeacon:didRangeBeaconsInRegion", function(event, pluginResult) {
if (!$scope.skip) {
$scope.skip = true;
$state.go('app.beacon');
}
});
$cordovaBeacon.startRangingBeaconsInRegion($cordovaBeacon.createBeaconRegion("abcdefg", "8484848484848484848"));
});
}
Thanks in advance for help.
Use Run
app.run(function('$scope', '$state', '$rootScope', '$ionicPlatform', '$cordovaBeacon'){
function homeCtrl($scope, $state, $rootScope, $ionicPlatform, $cordovaBeacon) {
$scope.skip = false;
$ionicPlatform.ready(function() {
$cordovaBeacon.requestWhenInUseAuthorization();
$rootScope.$on("$cordovaBeacon:didRangeBeaconsInRegion", function(event, pluginResult) {
if (!$scope.skip) {
$scope.skip = true;
$state.go('app.beacon');
}
});
$cordovaBeacon.startRangingBeaconsInRegion($cordovaBeacon.createBeaconRegion("abcdefg", "8484848484848484848"));
});
Run will be executed first before any controller is loaded or any service is injected.
ngInit is something that you need in your case
Whereever you're defining your app or controller you can point the method that you want to execute at the beginning of your app only once in ng-init attribute.
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="" ng-init="myText='Hello World!'">
<h1>{{myText}}</h1>
<p>The ng-init directive has created an AngularJS variable, which you can use in the application.</p>
</div>
</body>
</html>
source
However, angular docs strictly states that you should not use ngInit for initializing purposes. (see docs)
This directive can be abused to add unnecessary amounts of logic into
your templates. There are only a few appropriate uses of ngInit, such
as for aliasing special properties of ngRepeat, as seen in the demo
below; and for injecting data via server side scripting. Besides these
few cases, you should use controllers rather than ngInit to initialize
values on a scope.
Initializing values is something that should be done from controller. (see docs)
Use controllers to:
Set up the initial state of the $scope object. Add behavior to the
$scope object.

How to store usrename and make it accessible everywhere?

I have a text field:
<input type="text" ng-model="user">
and I have a button that will redirect to another page. On that page, I want to print the username typed in by the user. How can I do that?
My preference is ionic.
ionic works on top of angular. There are various ways by which you can achieve this functionality:
1) Use constants file to keep your value
Create a file called constants.js, include it in your index.html as:
<script src="Constants/Constants.js"></script>
declare key value pair combinations in it as:
var url_config = {
"USER_NAME" : "LOGIN_USER",
};
in your controller file, set the USER_NAME value as:
url_config.USER_NAME = $scope.user; //the model variable name that you had used
Use this value, where you want to access as:
$scope.loggedInUser = url_config.USER_NAME; // you will get the value here
The disadvantage here is that the value will get lost if you reload the screen. This can be ignored in android or ios app that you create using phonegap, the screens can't be refreshed, but if you are using web app this won't be a recommendable method.
2) Use a service to pass the constants
Create a utility service to keep the variable
angular.module('myApp').service('UtilityService', function () {
this.USER_NAME = '';
});
You can set this in your controller as:
angular.module('myApp')
.controller('LoginController', function ($scope, UtilityService) {
UtilityService.USER_NAME = $scope.user;
});
Access it in your other controller as:
angular.module('myApp')
.controller('UserController', function ($scope, UtilityService) {
$scope.loggedInUser = UtilityService.user;
});
This is a reliable way and a recommended method too.
3) Use local Storage
Here you can use the HTML5 feature of local storage to access the value from the browser's local storage.
Set the value in the login controller as:
angular.module('myApp')
.controller('LoginController', function ($scope, $localStorage) {
$localStorage.USER_NAME = $scope.loggedInUser;
});
In the receiving controller use it as:
angular.module('myApp')
.controller('UserController', function ($scope, $localStorage) {
$scope.loggedInUser = $localStorage.USER_NAME;
});
This will pertain the value even if the app goes to background or quits. Unless you clear the app cache or app data manually, the value will be saved.
For accessing $localStorage, you will require to use the ngStorage plugin that you can access from github and follow the instructions for instalation, then inject ngStorage as:
var myApp = angular.module('app', ['ngStorage']);
Now you are ready to use the $localStorage, provided you have included it in the controller where you are willing to access it.
4) Use session storage
Using the same ngStorage plugin you can use the session storage via $sessionStorage.
Set the value in the login controller as:
angular.module('myApp')
.controller('LoginController', function ($scope, $sessionStorage) {
$sessionStorage.USER_NAME = $scope.loggedInUser;
});
In the receiving controller use it as:
angular.module('myApp')
.controller('UserController', function ($scope, $sessionStorage) {
$scope.loggedInUser = $sessionStorage.USER_NAME;
});
Session storage keeps the data in session which gets expired after a limited time. This usage would be recommended for features like access tokens etc. For this scenario of username this won't be a recommended method
There are mainly two ways to achieve this:
1.By using Constants
app.js
angular.module('ionicApp', ['ionic'])
.constant('appConstant', {
user: ''
})
Controller
angular.module('ionicApp.home', ['ionic'])
.controller('homeCtrl', ['$state', 'appConstant', function($state, appConstant) {
'use strict';
$scope.user = '';
$scope.onClick = function() {
appConstant.user = $scope.user;
};
}]);
html
<input type="text" ng-model="user">
<button ng-click="onClick()">Submit</button>
Now you will get user name from any controllers by using appConstant.user
2.By using localstorage
Controller
angular.module('ionicApp.home', ['ionic'])
.controller('homeCtrl', ['$state', '$localStorage', function($state, $localStorage) {
'use strict';
$scope.user='';
$scope.onClick = function() {
$localStorage.set('user', user);
};
}]);
html
<input type="text" ng-model="user">
<button ng-click="onClick()">Submit</button>
Now you will get user name from any controllers by using $localStorage.get('user')

Angular JS - service not working

I am using a service to get data from the server using $http.get() method. I am calling the function in the service and then accessing its variable from the controller. But it is not working this way.
The code is below
'use strict';
var mission_vision_mod = angular.module('myApp.mission_vision', ['ngRoute']);
mission_vision_mod.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/mission_vision', {
templateUrl: 'partials/mission_vision/mission_vision.html',
controller: 'mission_visionCtrl'
});
}]);
mission_vision_mod.controller('mission_visionCtrl', ['$scope','getMissionData','$http', function($scope, $http, getMissionData) {
$scope.visiontext = "Here is the content of vision";
getMissionData.getmissiondata();
$scope.missions = getMissionData.missiondata;
$scope.len = $scope.missions.length;
}]);
mission_vision_mod.service('getMissionData', ['$rootScope','$http', function($rootScope, $http){
var missiondata;
function getmissiondata(){
$http.get('m_id.json').success(function(data){
missiondata = data;
});
}
}]);
When i write the$http.get() function in the controller itself, it works. I am new to angular JS.
Try writing your service like this
mission_vision_mod.service('getMissionData', ['$rootScope','$http', function($rootScope, $http){
this.getMissionData=function(){
return $http.get('m_id.json');
}
}]);
Use Service in controller like this:
mission_vision_mod.controller('mission_visionCtrl', ['$scope','getMissionData','$http', function($scope,getMissionData,$http) {
$scope.visiontext = "Here is the content of vision";
getMissionData.getMissionData().success(function(response){
$scope.missions=response;
$scope.len = $scope.missions.length;
}).error(function(errorl){
//handle error here
});
}]);
Also I suggest using a better name for service -'MissionDataService' :)
EDIT- Your sequence of injected service should match sequence of injectable names specified in the array..See my last edit
['$scope','getMissionData','$http',
function($scope, $http, getMissionData
The service names don't match with the variable names.
My advice: stop using this array notation. It clutters the code and is a frequent source of bugs. Use ng-annotate.
That said, your service is not correctly defined. It doesn't have any member function that would allow it to be called. Re-read the documentation of services. Defining services using factory() is easier than defining them using service(), BTW. And the service should return the promise returned by $http. Trying to access the value returned by an asynchronous call right after making the asynchronous call will never work. Read http://blog.ninja-squad.com/2015/05/28/angularjs-promises/
Try:
mission_vision_mod.service('getMissionData', ['$rootScope','$http', function($rootScope, $http){
var missiondata;
function getmissiondata(){
$http.get('m_id.json').success(function(data){
missiondata = data;
return missiondata;
});
}
}]);

resolve in angularjs not working

I would like to load my data before the route changes and using
$routeChangeSuccess
or
$routeChangeStart
will not help and would like to do it using resolve in angular routing. So when ever a route change, i use resolve and load the data and when that is done i have the data ready to be bound on the templateUrl that the route will serve
i am not sure if i am doing this correct but can any one please explain why this plnk is not working
You are not injecting the 'mydata' into your controller. I suggest using two controllers, since mydata is not defined until you resolve the route.
var CampaignController = function ($scope, mydata) {
$scope.mydata = mydata;
};
var mainController = function ($scope) {
$scope.mydata = "mydata";
};
CampaignController.$inject = ['$scope', 'mydata'];
mainController.$inject = ['$scope'];
var ngApp = angular.module('ngApp', ['ngRoute']);
ngApp.controller('CampaignController', CampaignController);
ngApp.controller('mainController', mainController);
here is an updated plnk

Passing variables to angular.js scope from web page

What is correct way of passing variables from web page when initializing $scope?
I currently know 2 possibilities:
ng-init, which looks awful and not recommended (?)
using AJAX request for resource, which requires additional request to server which I do not want.
Is there any other way?
If those variables are able to be injected through ng-init, I'm assuming you have them declared in Javascript.
So you should create a service (constant) to share these variables:
var variablesFromWebPage = ...;
app.constant('initValues', variablesFromWebPage);
With this service, you don't need to add them to the scope in the app start, you can use it from any controller you have, just by injecting it (function MyCtrl(initValues) {}).
Althouhg, if you do require it to be in the scope, then this is one of the main reasons what controllers are meant for, as per the docs:
Use controllers to:
Set up the initial state of a scope object.
Add behavior to the scope object.
Just add this cotroller to your root node:
app.controller('InitCtrl', function($rootScope, initValues) {
$rootScope.variable1 = initValue.someVariable;
$rootScope.variable2 = initValue.anotherVariable;
});
#Cunha: Tnx.
Here some more details how I did it:
In the Webpage:
<script type="text/javascript">
var variablesFromWebPage = {};
variablesFromWebPage.phoneNumber = '#Model.PhoneNumber';
</script>
In the angular application file, registering the service:
var module= angular.module('mymodule', ['ngRoute', 'ngAnimate']);
module.factory('variablesFromWebPage', function () {
return variablesFromWebPage
});
And then the controller:
module.controller('IndexController',
function ($scope, $location, $http, $interval, variablesFromWebPage) {
$scope.phoneNumber = variablesFromWebPage.phoneNumber;
}
);

Resources