angularjs 1 manual bootstrap doesnot work - javascript

I am new to angularjs.
I tried to create 2 different modules in an single js file and them manually bootstrap one of them to a element. This was suggested in one of the stackoverflow questions. But this doesnot seem to work.
Both of the modules work fine independently.
I am not sure what is going wrong here.
Here's my code :-
myApp.js
var app = angular.module("myApp", []);
var myController = app.controller("ctrl1", function($scope){
"use strict";
$scope.fname = "Bill";
$scope.lname = "Goldberg";
$scope.updatevalue = function () {
$scope.fullname = $scope.fname + $scope.lname;
//$scope.fname = "newName"
};
});
app.directive("w3TestDirective", function() {
"use strict";
return {
template : "<h1>This is my life!</h1>"
};
});
var loginController = angular.module('loginController', []);
loginController.controller('loginCntrl', function ($scope) {
"use strict";
$scope.username="email";
$scope.password="password";
$scope.present = false;
$scope.login = function () {
"use strict";
if ($scope.username == "Amar" & $scope.password == "Amar") {
$scope.present=true;
$scope.loginMessage = "logged in successfully";
} else {
$scope.present=true;
$scope.loginMessage = "Invalid username or password";
}
}
});
angular.bootstrap(document.getElementById("loginDiv"),['loginController']);
Index.html
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<!--script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular-route.js"></script-->
<script src="scripts/services/myApp.js"></script>
<!--script src="scripts/services/login.js"></script-->
<body>
<div id="demoDiv" ng-app="myApp" ng-controller="ctrl1">
<span>Values:</span>
<input type="text" ng-model="fname"/>
<input type="text" ng-model="lname"/>
<button ng-click="updatevalue()">fullname</button>
<br></br>
{{ fullname }}
<br></br>
<w3-test-directive></w3-test-directive>
</div>
<br></br>
<div id="loginDiv" ng-app="loginController" ng-controller="loginCntrl">
<input type="text" ng-model="username"/>
<input type="text" ng-model="password"/>
<button ng-click="login()">submit</button>
<br></br>
<div ng-if="present"> {{ loginMessage }} </div>
</div>
</body>
</html>

This is the completely wrong approach. You CAN have your controllers in more than one module, but you should always have a single module which is the main parent for the app.
Let's Assume myApp is your parent module, and make some changes:
First, move the ng-app to the body element:
<body ng-app="myApp">
<div id="demoDiv" ng-controller="ctrl1">
...
Next, remove ng-app from the loginDiv:
<div id="loginDiv" ng-controller="loginCntrl">
Finally, inject the loginController module into the myApp module:
var app = angular.module("myApp", ['loginController']);
Now, the app will be able to attach both controllers without issue.
http://plnkr.co/edit/rkFY0ASCHaQUTByaHJg3?p=preview

I fixed my issue with the following code :-
var app = angular.module("myApp", ['utilModule','loginModule']);
var myController = app.controller("ctrl1", function($scope){
"use strict";
$scope.fname = "Bill";
$scope.lname = "Goldberg";
$scope.updatevalue = function () {
$scope.fullname = $scope.fname + $scope.lname;
//$scope.fname = "newName"
};
});
app.directive("w3TestDirective", function() {
"use strict";
return {
template : "<h1>This is my life!</h1>"
};
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<!--script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular-route.js"></script-->
<script src="scripts/services/myApp.js"></script>
<script src="scripts/services/util.js"></script>
<script src="scripts/services/login.js"></script>
<body ng-app="myApp">
<div id="demoDiv" ng-controller="ctrl1">
<span>Values:</span>
<input type="text" ng-model="fname"/>
<input type="text" ng-model="lname"/>
<button ng-click="updatevalue()">fullname</button>
<br></br>
{{ fullname }}
<br></br>
<div ng-controller="utilCntrl">
{{ test }}
<testDirective></testDirective>
</div>
<w3-test-directive></w3-test-directive>
</div>
<br></br>
<div id="loginDiv" ng-controller="loginCntrl">
<input type="text" ng-model="username"/>
<input type="text" ng-model="password"/>
<button ng-click="login()">submit</button>
<br></br>
<div ng-if="present"> {{ loginMessage }} </div>
</div>
</body>
</html>
There is only 1 issue, the testDirective tag doesnot print anything on the browser. but that is not a requirement, so I will just ignore this for the time being.
I realize that this is what #Claies has posted. Claies, Thank you very much for your time and effort.

You can't use the ng-app directive and angular.bootstrap function to bootstrap you angular application. You either use ng-app or angular.bootstrap.
If you have two modules "myApp" and "loginController" like you do in your app, you must make "loginController" a dependency of "myApp". "myApp" will be your angular application module that you can add more dependencies, external or custom.
angular.module('myApp', ['loginController', 'ui-router', 'etc'...])

Related

Getting coordinates from ngMap auto-complete

Google maps allows one to get the coordinates from the auto-complete library. I cannot seem to find a way of doing it with ngMap without involving the "controller as" syntax. I want to get the coordinates and output them to console with just $scope.
var app = angular.module("App", ["ngMap"]);
app.controller("MyCtrl", function ($scope, NgMap) {
$scope.placeChanged = function placeChanged() {
var place = this.getPlace();
console.log(place.place.geometry.location)
};
});
<html ng-app="App">
<script src="https://maps.google.com/maps/api/js?libraries=places"></script>
<script src="https://code.angularjs.org/1.3.15/angular.js"></script>
<script src="https://rawgit.com/allenhwkim/angularjs-google-maps/master/build/scripts/ng-map.js"></script>
<div ng-controller="MyCtrl">
<input type="text" name="address" places-auto-complete ng-model="address" on-place-change="placeChanged()">
</div>
</html>
Directive places-auto-complete has on-place-changed in NgMap
html:
<div ng-controller="MyCtrl">
<input places-auto-complete ng-model='address' on-place-changed="getCoords()" />
</div>
Script: when the place changes ng-model is updated and the
var app = angular.module("App", ["ngMap"]);
app.controller("MyCtrl", function($scope, NgMap) {
$scope.address = '';
$scope.getCoords = function() {
NgMap.getGeoLocation($scope.address).then(function(latlng) {
console.log(latlng.lat());
console.log(latlng.lng());
});
};
})

Angularjs - Displaying data using $http get from remote server

i want to send a http get request which is not a problem.
But the problem is i want to disply the data from the server page. Does it has to be a JSON page to display the data from remote server ? or any sort of data can be displayed ? if yes , then how
Thank you
<div class="form" ng-app="myApp" ng-controller="myCtrl">
<p>Enter URL : <input type="text" ng-model="url" /></p>
<p><input type="submit" value="CHECK" ng-click="callAPI()" /> </p> <!-- 1 -->
<p>
<ul ng-repeat="post in posts">
<li>{{post}}</li>
</ul>
</p>
<div ng-bind="result"></div> <!-- 5 -->
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$scope.callAPI = function() { // 2
//console.log($scope.url); //3
$http.get($scope.url)
.success(function(response) {
$scope.posts = response.data; //4
});
};
});
</script>
</body>
</html>
another version of code
<div class="form" ng-app="myApp" ng-controller="myCtrl">
<p>Enter URL : <input type="text" ng-model="url" /></p>
<p><input type="submit" value="CHECK" ng-click="callAPI()" /> </p>
<div ng-bind="result"></div> <!-- 5 -->
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$scope.$watch('url', function() {
fetch();
});
function fetch() {
console.log($scope.url);
$http.get($scope.url)
.success(function(response) {
$scope.result = response.data;
});
}
$scope.callAPI= function() {
this.setSelectionRange(0, this.value.length);
}
});
</script>
</body>
</html>
Like the comments says, I believe that angular look at the content Type of the response to parse the data. Have you try added the accept header type?
What is the content type of the response?
var req = {
method: 'GET',
url: 'http://example.com',
headers: {
'Accept': change this to whatever content you want to accept
},
data: { test: 'test' }
}
$http(req).then(function(){...}, function(){...});
hey i have found my answer of my question ...
there was a mistake in the source code
here is the right one
<div class="form" ng-app="myApp" ng-controller="myCtrl as controller">
<p>Enter URL : <input type="text" ng-model="url" /></p>
<p><input type="submit" value="CHECK" ng-click="clickButton()" /> </p>
<p>
<ul>
<li ng-repeat="data in result">
{{data}}
</li>
</ul>
</p>
</div>
and
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$scope.clickButton = function() {
console.log($scope.url);
$http.get($scope.url)
.then(function(response) {
$scope.result = response.data;
});
};
});
</script>
:)
if anyone has a similer problem , i hope this answer will help ..
cheers
function functionName(){
$http.get(URL).success(function(response){
$scope.variable = response;
})
}
inside get() put your url, if your url returning any data then it will go to success() function.

How to share data between controllers in AngularJS? [duplicate]

This question already has answers here:
Share data between AngularJS controllers
(11 answers)
Closed 6 years ago.
I have a team_list page and a team page. A user will have a list of teams they are in in the team_list page and then click on one of the teams to go to its team page. I am not sure how to send the data that the team page that the user is going to is Team A's teampage or Team B's team page. So how do I share data between controllers?
I know I should be using services but I'm not sure how to use them in this context..I've tried some methods and commented out some but I'm still not sure how to go about this.
Using node.js and express framework for backend
team_list.html:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<head>
<title>Team List</title>
</head>
<body>
<h1>
Welcome to Your Team List Page!
</h1>
<!--<div ng-app="teamListPage" ng-controller="listController">
<fieldset>
<legend>Your Teams</legend>
<ul>
<li ng-repeat="x in [dave, david, darrell]">{{x}}</li>
<input type="button" id="enter" name="enter" value="Enter Home Page" ng-click="enterTeamPage()"/>
</ul>
</fieldset>
</div>-->
<div ng-app="teamListPage" ng-controller="listController">
<li ng-repeat="x in records">
{{x.team_name}}<br/>
<input type="button" id="enter" name="enter" value="Enter Home Page" ng-click="enterTeamPage()"/>
</li>
<input type="button" id="Create" name="Create" value="Create New Team" ng-click="enterCreateTeamPage()" />
</div>
<script>
var page = angular.module('teamListPage', []);
/*page.factory('myService', function() {
var user_id = [];
var setUserID = function(newObj) {
user_id.push(newObj);
};
var getUserID = function(){
return user_id;
};
return {
setUserID: setUserID,
getUserID: getUserID
};
});*/
page.factory('myService', function(){
return {
data: {
user_ID: ''
},
update: function(userID) {
// Improve this method as needed
this.data.user_ID = userID;
}
};
});
page.controller('listController', function($scope, $http, $window, myService) {
console.log(myService.data);
var login_http = $http({
method: 'GET',
url: '/team_req',
params: { user_id: 1 }
}).then(
function (response) {
//$window.alert(response.data[0].team_name);
$scope.records = response.data;
//console.log($scope.records[1]);
//alert('successfull ...');
}, function (response) {
$window.alert('wrong username/password');
}
)
$scope.enterTeamPage = function() {
$window.location.href = '/teamPage';
};
$scope.enterCreateTeamPage = function() {
$window.location.href = '/createTeamPage';
};
})
</script>
</body>
</html>
team_page.html:
<!DOCTYPE html>
<html lang="en">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<head>
<meta charset="UTF-8">
<title>Team Page</title>
</head>
<body>
<h1>
Team Page
</h1>
<div ng-app="teamPage" ng-controller="teamController">
<form id="Communication Board">
<fieldset>
<legend>COMMUNICATION BOARD</legend>
<h3>
chat feature coming up!
</h3>
<legend>videocall</legend>
<h4>
video call feature coming up!
</h4>
<legend>screenshare</legend>
<h5>
screenshare feature coming up!
</h5>
</fieldset>
</form>
<form id="Data Board" action="">
<fieldset>
<legend>DATA BOARD</legend>
<h6>
calendar feature coming up!
</h6>
<legend>announcements</legend>
<h7>
All features are coming up very soon!
</h7>
</fieldset>
</form>
<p>
<input type="button" id="CodingZone" name="CodingZone" value="Go to Coding Zone" ng-click="enterCodingPage()" />
</p>
</div>
<script>
var page = angular.module('teamPage', []);
page.controller('teamController', function($scope, $http, $window) {
//get the history of the chat board
$scope.getChatHistory = function() {
var create = $http({
method: 'Get',
url: '/chatHistory'
}).then(
function successful(response) {
$scope.theResponse = response.data;
}, function unsuccessful(response) {
alert('got an error back from server');
$scope.theResponse = response;
});
}
$scope.enterCodingPage = function() {
$window.location.href = '/codingPage';
};
})
</script>
</body>
</html>
Also should I put my service in app.js or index.js?
The best way to share data between controllers or components (wrappers for directives) is to use angular services and inject them into controllers. Cuz services are singletons so each of them presents single state for all components where it will be injected.

Routing issues in Angular

I'm pretty new to Angular and I came across an issue I can't get around. I did see other people asking the same question, however their problem had to do with a missing ['ngRoute'] .I checked the code many times,but I might have missed something so I'm really hoping I can get some help on this one. Thanks in advance !
directories http://i.stack.imgur.com/zvaqU.png
firstpage.html :
<html ng-app="myApp">
<head>
</head>
<body>
<div ng-view></div>
<script
src="angular.min.js">
</script>
<script
src="angular-route.js">
</script>
<script
src="test.js">
</script>
</body>
</html>
test.js :
var app = angular.module('myApp',['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider
.when('/',
{
controller: 'SimpleController',
templateUrl: 'Partials/View1.html'
})
.when('/view2',
{
controller: 'SimpleController',
templateUrl: 'Partials/View2.html'
})
.otherwise({redirectTo:'/'});
});
var controllers = {};
controllers.SimpleController = function ($scope) {
$scope.djs=[{name:'Adam Beyer',city:'Sweden',djRank:1},
{name:'Joseph Capriati',city:'Napoli',djRank:4},
{name:'Nina Kraviz',city: 'Moscow',djRank:7},
{name:'Adam Petrov',city:'Sofia',djRank:100}];
$scope.addCustomer() = function () {
$scope.djs.push({name:$scope.newCustomer.name,
city:$scope.newCustomer.city});
};
};
app.controller(controllers);
View1.html :
<div class = "container">
<h2>View 1</h2>
Name:
<br/>
<input ng-model="filter.name" />
<br/>
<ul>
<li ng-repeat="dj in djs|filter:filter.name|orderBy:'djRank'"> {{dj.name}}
</li>
</ul>
<br/>
Customer Name: <br/>
<input type="text" ng-model="customer.name" />
<br/>
Customer City: <br/>
<input type="text" ng-model = "customer.city" />
<br/>
<button ng-click="addCustomer()">Add Customer</button>
</div>
View2.html :
<div class="container">
<h2>View 2</h2>
City:
<br/>
<input type = "text" ng-model="city" />
<br/>
<ul>
<li ng-repeat= "dj in djs |filter:city"</li>
</ul>
</div>
You made a typo in your controller. It should be
$scope.addCustomer = function () {
$scope.djs.push({name:$scope.newCustomer.name,
city:$scope.newCustomer.city});
};
not
$scope.addCustomer() = function () {
$scope.djs.push({name:$scope.newCustomer.name,
city:$scope.newCustomer.city});
};
Notice the parentheses right after addCustomer should not be there.

Show/hide button using ng-show

I've got a problem related to the visibility of a button. I have to hide a button when there is no text in the form field, and show it back when it's filled. I've got some code:
<div class="TextAreaCont">
<input ng-model="pageUrl" placeholder="Facebook Page URL" type="text">
</div>
<div class="ButtonCont" ng-show="ctrl.isButtonVisible()">
<button ng-click="ctrl.send()">Fetch data</button>
</div>
And I wrote it:
Facebook.controller('PageCtrl', ['$scope', function($scope){
$scope.isButtonVisible = function(){
if($scope.pageUrl){return true}else{return false}
};
Where is the problem?
To be honest, I've never leart JS and Angular.
Here is my solution
var Facebook = angular.module('Facebook', []);
Facebook.controller('PageCtrl', [function(){
var ctrl = this;
ctrl.isButtonVisible = function(){
if(ctrl.pageUrl){
return true;
}else{
return false;
}
};
ctrl.send = function(){
console.log('Page URL: ' + ctrl.pageUrl)
};
}]);
See Plunker for more details.
Few problems that I can spot in your original code:
when using controller as syntax, use 'this' keyword, not $scope inside your controller
ng-model="pageUrl" should be ng-model="ctrl.pageUrl"
Just FYI, isButtonVisible() will be evaluated on every digest cycle, so there no need for watchers of ng-change.
try this.
i put simple example.
var app = angular.module('app', []);
app.controller('TestController', function ($scope) {
$scope.display = false;
$scope.isButtonVisible = function(pageUrl){
if(pageUrl){
$scope.display = true;
}
else{$scope.display = false;}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="TestController">
<input ng-model="pageUrl" placeholder="Facebook Page URL" type="text" ng-change="isButtonVisible(pageUrl)">
<div class="ButtonCont" ng-show="display">
<button ng-click="send()">Fetch data</button>
</div>
<input ng-model="pageUrl2" placeholder="Facebook Page URL" type="text" ng-change="isButtonVisible(pageUrl)">
<div class="ButtonCont" ng-show="pageUrl2">
<button ng-click="send()">Fetch data</button>
</div>
</div>

Categories

Resources