Here is my app.js
var app = angular.module("app",[]);
app.controller("myFirstController",['$scope',function($scope){
$scope.test = "myfirstName";
$scope.test1 = "myfirstName";
}])
app.controller("mySecondController",['$scope','$rootScope',function($scope,$rootScope){
$scope.test = "myLastName";
//Here how to call my test,test1 scope using $rootScope ??
}])
Can i do this using $rootScope?I dont want to use any emit and broadcast or this
if you store any value in rootscope like :
$rootScope.test =" value ";
and you can retrieve value from the rootScope like
var value = $rootScope.test;
But it's not good to use for data maintenance and security
because if you refresh browser, then all scope values are cleared.
So I will suggest you for 3 varies ways
$cookies
$ngStorage
$Service
Broadcast
I dont want to use any emit and broadcast or
But that's the only way is best to pass value from one controller to another controller
you can do like below but use different names for avoiding errors in some cases.if you doesn't declare it as $rootScope in first ctrl then it will be undef in second ctrl
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
<script src="app.js"></script>
</head>
<body >
<div ng-controller="myFirstController">
</div>
<div ng-controller="mySecondController">
</div>
</body>
<script>
var app = angular.module('plunker', []);
app.controller("myFirstController",['$scope','$rootScope',function($scope,$rootScope){
$rootScope.test = "myfirstName";
}])
app.controller("mySecondController",['$scope','$rootScope',function($scope,$rootScope){
$scope.test = "myLastName";
console.log($rootScope.test);
//Here how to call my myFirstName scope using $rootScope ??
}])
</script>
</html>
Related
I'm trying to get my head around learning $compile but just looking for a couple of pointers as to where I'm going wrong...
var app = angular.module("App", []);
app.controller("Ctrl", function ($scope, $http, $compile) {
}).directive('myDir', function ($compile) {
$(document).on("click", "#button", function ($compile) {
var newDirective = angular.element('<li>{{app data}}</li>');
$(".grid ul").append(newDirective);
$compile(newDirective)($scope);
});
});
I suppose firstly, nothing seems to work when I put it into my directory but it does when I put it in the controller. And secondly it doesn't seem to compile as the Angular tags/elements don't render correctly. I just can't figure out where I'm going wrong...
As per the Docs $compille
Compiles an HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together.
You are on the right track to use it , just need some modification in your directive code like this.
var app = angular.module("App", []);
app.controller("Ctrl", function ($scope, $http, $compile) {
}).directive('myDir', function ($compile) {
return{
restrict: 'A',
scope: {
data:"=appdata"
},
link: function(scope,element){
var newDirective = angular.element('<li>'+ scope.data +'</li>');
var content = $compile(newDirective)(scope);
element.append(content);
}
}
});
<!DOCTYPE html>
<html ng-app="App">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
<script src="app.js"></script>
</head>
<body ng-controller="Ctrl">
<div class="grid" >
Hello
<ul my-dir appdata="'whatever'">
</ul>
</div>
</body>
</html>
Plunker : https://plnkr.co/edit/xqgnhXnVoYOsXFhPMbOY?p=preview
Your directive is not formatted (created) correct. No need to use JQUERY... you are compiling the html and the data ($scope) but you are not applying the compiled template to your html.
Check this plunkr: https://plnkr.co/edit/eKdIEhyLBViWAOzfWhhV?p=preview
angular.module('plunker', [])
.directive('compileDir', ['$rootScope', '$compile', compileDir])
.controller('HomeController', [HomeController]);
function compileDir($rootScope, $compile) {
var self = {};
self.restrict = 'A';
self.scope = {
compileDirOptions: '='
};
self.link = linkFn;
return self;
function linkFn($scope, $element, $attributes) {
// I am making a new scope because I do not want to mess the directive's one, you do not have to
var newScope = angular.merge($rootScope.$new(), $scope.compileDirOptions.data);
var el = $compile($scope.compileDirOptions.html)(newScope);
$element.append(el);
}
}
function HomeController() {
var self = this;
self.message = "Hello World!";
self.data = {
html: '<li>{{name}}</li><li>{{color}}</li>',
data: {
name: 'app data',
color: 'red'
}
}
}
Your html is like this:
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.5.x" src="https://code.angularjs.org/1.5.8/angular.js" data-semver="1.5.8"></script>
<script src="app.js"></script>
</head>
<body ng-controller="HomeController as home">
<ul compile-dir compile-dir-options="home.data"></ul>
</body>
</html>
For some reason it gives me the error:
ReferenceError: random is not defined at Scope.$scope.generateRandom
I dont know what im doing wrong, you can go check out the website im using to do this HERE.
index.html:
<!DOCTYPE html>
<html lang= "en">
<head>
<meta charset="UTF-8" />
<title>Basic Login Form</title>
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.8/angular.js" data-semver="1.4.8"></script>
<script src = "https://rawgit.com/nirus/Angular-Route-Injector/master/dist/routeInjector.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular-route.js"></script>
<script type="text/javascript" src="script23.js"></script>
</head>
<body ng-app = "app" ng-controller = "app">
<button ng-click = "generateRandom()">Generate Random Number</button>
<br> {{randomNumber}}
</body>
</html>
script23.js:
var app = angular.module('app', []);
app.service('random', function(){
var randomNum = Math.floor(Math.random()*10)
this.generate = function(){
return randomNum;
}
});
app.controller('app' , function($scope){
$scope.generateRandom = function(){
alert("Something")
$scope.randomNumber = random.generate();
}
})
To use service in controller, you need to inject it.
app.controller('app', function ($scope, random) {
I'd recommend you to use following syntax:
app.controller('app', ['$scope', 'random', function ($scope, random) {
See Why we Inject our dependencies two times in angularjs?
Change your controller like this, since you are using the service 'random'
myApp.controller('app', ['$scope','random', function( $scope,random)
{
$scope.generateRandom = function(){
alert("Something")
$scope.randomNumber = random.generate();
}
}])
Here is the working Application
I'm trying to learn Angular.js. I set up a simple page, in which I want to display a message from my script file. Here's the HTML structure:
<!DOCTYPE html>
<html ng-app>
<head>
<script data-require="angular.js#*" data-semver="2.0.0-alpha.31" src="https://code.angularjs.org/2.0.0-alpha.31/angular.js"></script>
<link href="style.css" rel="stylesheet" />
<script src="script.js"></script>
</head>
<body ng-controller="MainController">
<h1>{{message}}</h1>
</body>
</html>
And this is my script.js:
var MainController = function($scope){
$scope.message = "my message";
};
I'm supposed to see the words my message on the page, but instead I'm seeing literally {{message}}. I tried to wrap the JS code in self-envoking function:
(function() {
var MainController = function($scope) {
$scope.message = "my message";
};
}());
But it didn't have any result.
What am I doing wrong?
It's old syntax and you cannot declare controller like that. Now you need to register controller on your module.
angular.module('anyModuleName',[]).controller('yourControllerName',function(){
});
and also edit to ng-app="anyModuleName" where you initialize your app. In your case <html ng-app="anyModuleName">
I want to set hidden input value on login user then i want to get hidden input value in another page.
index.html (This page has hidden input )
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="lib/ionic/ng-cordova-master/demo/www/lib/ngCordova/dist/ng-cordova.js"></script>
<script src="cordova.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<script src="js/services.js"></script>
</head>
<body ng-app="starter">
<input type="hidden" id="hiddenValue" ng-value="hiddenValue" />
<ion-nav-view></ion-nav-view>
</body>
</html>
I set hidden input value then i use $location.path('/HomePage'); in order to redirect as below
Login.html's controller as below
.controller('LoginCtrl', function ($scope, LoginService, $ionicPopup, $state, $location) {
$scope.data = {};
$scope.login = function () {
LoginService.loginUser($scope.data.username, $scope.data.password).success(function (data) {
$scope.hiddenValue = "TestValue"; // I set value here
$location.path('/Menu');
}).error(function (data) {
var alertPopup = $ionicPopup.alert({
title: 'Login failed!',
template: 'Please check your credentials!'
});
});
}
})
I can not display $scope.hiddenValue in Menu.html in below side.
.controller('MenuCtrl', function ($scope, LoginService, $ionicPopup, $state, $location) {
alert($scope.hiddenValue);
})
when i try to use alert($scope.hiddenValue); in order to display value from hidden input , i get undefined error
Where i miss why i can not display value in another page ?
<input type="hidden" id="hiddenValue" ng-value="hiddenValue" />
is not falling inside the scope of the loginCtrl.
$scope.hiddenValue = "TestValue"; statetment in the loginCtrl will assign TestValue to the $scope of LoginCtrl.
You can create a service "user" and have this.user == '';
.service('user', function () {
this.user = '';
this.setUser = function(name) {
this.user = name;
}
});
Inject this "user" service in controllers you need to share the name. And also set the value using the user.setUser('test') in your LoginCtrl controller.
It looks like you want to share data between controllers which is quite a common need. Looking at something like this might help you - AngularJS: How can I pass variables between controllers?
The best way is to use an AngularJS service or factory.
I am aware that I cannot set the value of an input when Ng-Nodel is referenced, but I am trying to find a work around.
The html value is being pulled from the URL variable (such as full name or email) that the user has entered in the previous page. Ng-model is being used to store these information. - signUp.php?user_email=$email&fname=$fullNam
Below is an example of what I mean,
<?php
$email = $_GET['user_email'];
$fullName = $_GET['fname'];
?>
<input id="signupformItem" ng-model="user.username" type="email" name="email" value= <?php echo $email; ?> placeholder="Email Address" required> <br>
Any help would be greatly appreciated
I just created a demo for you but I will recommend you to go through some series of tutorial to get better knowledge of the framework or technology(angularjs and javascript) you are going to use in your project.
I created plunk for you. You can visit it here.
Javascript code
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, userService) {
$scope.name = 'World';
$scope.userName = userService.getUsers();
userService.getUserAjax()
.success(function(response) {$scope.names = response[0].Name;});
});
app.service('userService', function($http){
var fac = {};
fac.getUserAjax = function() {
return $http.get("http://www.w3schools.com//website/Customers_JSON.php");
};
fac.getUsers = function(){ return 'John'};
return fac;
});
HTML code
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.3.x" src="https://code.angularjs.org/1.3.13/angular.js" data-semver="1.3.13"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
by {{userName}}
<p>username loaded by ajax :{{names}}</p>
</body>
</html>
You need to define one service that communicate to your web page using ajax service provided by angular ($http) and call it from the controller and on the success function just pick up the value and assign it to your scope variable. In your case username.
I just used w3schools service url here just for demonstration which would give me a list of users you need to implement php code that would return what you want and use it like described above.
I hope it would have given you basic idea of how to setup angular code to communicate to the server.