I am just playing around with AngularJS and I wrote a small piece of code which I have shared here. But for some reason, the binding of data doesnt happen. Here is the HTML and JS code for those who do not want to go to the plucker site.
first.html
<!doctype html>
<html ng-app="firstApp">
<head>
<title>First Angular JS</title>
<script src="/lib/angular.min.js"></script>
<script src="/js/first.js"></script>
</head>
<body>
<div ng-controller="FirstController">
<span>Name:</span>
<input type="text" ng-model="first">
<input type="text" ng-model="last">
<button ng-click='updateMessage()'>Message</button>
<hr>{{heading + message}}
</div>
</body>
</html>
first.js
var firstApp = angular.module('firstApp',[]);
firstApp.controller = ('FirstController',function($scope)
{
$scope.first = "Some";
$scope.last = "one";
$scope.heading = "Message: ";
$scope.updateMessage = function()
{
$scope.message = 'Hello' + $scope.first + ' ' + $scope.last + '!';
};
});
In the HTML, I am using express to redirect calls to its appropriate places
node_server.js
var express = require('express');
var app = express();
app.use('/', express.static('./static')).
use('/images',express.static('./images')).
use('/lib',express.static('./lib/angular-1.2.22'));
app.listen(8080);
The output is showing {{message + heading}}. Does anyone have any ideas why this wouldnt work?
The issue is in the way you're declaring your controller.
You have:
firstApp.controller = ('FirstController',function($scope) ...
It should be:
firstApp.controller('FirstController', function($scope) ...
Try this:
firstApp.controller('FirstController', ['$scope', function($scope) { ...
Doc's for controller in Angular
Related
I have a string like var message = "you are moving to {{output.number}}";
I want this to be put to div element. i tried using $("#message").html(message);
but it just printed the whole string for me. I want to have the output.number print the value it had. Is it possible to achieve what i want?
I am using angular.js 1.5.
Use $interpolate service like:
var message = $interpolate("you are moving to {{number}}")(output)
// or
var message = $interpolate("you are moving to {{output.number}}")($scope)
I hope you are looking for something like this. You can do it by using the scope variable inside the controller.
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.bootcss.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<input type="number" ng-model="output.number" />
<button ng-click="AppendItem()">Append</button>
<div id="message"></div>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
$scope.output = {};
$scope.AppendItem = function () {
var string = "Your Number is " + $scope.output.number;
$("#message").html(string);
}
});
</script>
</body>
</html>
You are almost there just try :
$scope.output.number = '123';
var message = "you are moving to" + output.number;
$("#message").html(message);
Don't put variable inside "" quotes.
When we are going to append a string variable to another string variable then we need to use append operator ie., "+". Here is an example.
var output.number = 10;
var message = "you are moving to " + output.number;
$("#message").html(message);
You can do like this using $compile:
$compile(angular.element(document.querySelectorAll('#message')[0]).html("you are moving to {{output.number}}"))($scope);
Add $compile as dependency in your controller.
All the best.
You can try this:
<html ng-app="app">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body ng-controller="appCtrl">
<p id="message"></p>
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"> </script>
</body>
JS:
Should not write DOM Manipulation code inside controller, but can get the idea how to do it.
var app = angular.module('app', []);
app.controller('appCtrl', function($scope, $interpolate){
var msg = "you are moving to {{number}}";
$scope.number = 10;
$('#message').html($interpolate(msg)($scope));
});
I am serving a static html file using the app.use(express.static(__dirname+"views")). And when I go to localhost:3000/first.html I get the html file. But I don't know if the angularjs and other controller javascript files were executed. I think they were not executed because I use ng-model for a button's value and it's just an empty button with no text and the function is not executed for the ng-click.
I think maybe it's because only the html file is served by the server without my controller js and my downloaded angularjs which I have src'd to in the html. But I don't see a 404 or any error in the console.
And also, when I use a virtual path(like app.use(express.static('',__dirname+"/views"))), I don't get the html file when I go to localhost:3000/views/first.html.
This is my server.js:
(function(){
var http = require("http");
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var path = require('path');
// app.use(express.static(__dirname));
app.use(bodyParser.json());
app.use(express.static(__dirname+'/views'));
// app.use(express.static('/views',__dirname+'/views')); this is not working
var server = http.createServer(app);
server.listen('3000');
console.log("Server is listening");
})();
My first.html which is served by the server:
<!DOCTYPE html>
<html ng-app="myapp">
<head>
<title></title>
<base href="localhost:3000/">
</head>
<body>
<script type="text/javascript" src="./angular.js"></script>
<script type="text/javascript" src="./angular-route.js"></script>
<script type="text/javascript" src="./controller.js"></script>
<div ng-controller="firstController">
First name:<input type="text" ng-model="firstName"><br>
Last name:<input type="text" ng-model="lastName"><br>
<input type="button" ng-click="loadView()" ng-model="submit" name="">
</div>
</body>
</html>
This is the controller.js:
var app = angular.module('myapp', ['ngRoute']);
app.config(function($routeProvider,$locationProvider){
$routeProvider.when('/first',{
templateUrl:'/first.html',
controller: 'firstController'
})
.when('/second',{
templateUrl:'/second.html',
controller:'secondController'
})
.otherwise({
redirectTo:'/first'
})
$locationProvider.html5Mode(true);
})
console.log("controller");
app.controller('firstController',function($scope,$location){
$scope.firstName="";
$scope.lastName="";
$scope.loadView = function()
{
$location.path('views/second/'+$scope.firstName +"/" +$scope.lastName);
}
$scope.submit = "submit";
})
.controller('secondController',function($scope,$routeParams){
$scope.firstName = $routeParams.firstName;
$scope.lastName = $routeParams.lastName;
})
Do I need to place the files in a local-server or any server to get the results?
index.html:
<!DOCTYPE html>
<html lang = "en">
<head>
<meta char-set = "UTF-8">
<title>AngularJS | Passing Data between Different Scopes</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular.min.js"></script>
<script src = "controller.js"></script>
</head>
<body ng-app = "mainApp">
<div ng-controller = "app">
<li ng-repeat = "i in myRange">
{{i}} <br/>
</li>
</div>
</body>
</html>
controller.js:
var app = angular.module('mainApp', []);
app.controller('app', function($scope) {
var range = 10;
var myRange = [];
for (i = 0; i<range; i++)
{
myRange.push(i);
}
$scope.myRange = myRange;
});
When i'm running using localhost it gets the result i wanted. But when I run it without using any server or local-server it shows only the html page, not returning data from controller.js file. As i know this must work without using of any local-server. what's the wrong here?
Edit:
When i run the html file without using local-server the output is as follows.
As #csharpfolk suggested, the problem is with loading angular.js library use 'https://' instead of '//'. If you use '//' browser will try to load using 'file://' protocol.
I am having problem with Angularjs view. Somehow i am doing something wrong and don't know where is the problem. Hope someone can help me out.
The problem is {{user.login}} (userRepoInfo.html file) does not get called at all from the controller and if i do console.log it is coming through fine from services. I am definitely doing something wrong between view and controller
I have five files
1) gitHubApiServices.js
2) gitHubApiController.js
3) userRepoInfo.html
4) app.js
5) index.html
Below is gitHubApiServices.js
(function() {
var gitHubApiFactory = function($http) {
var factory = {};
factory.getUserName = function(userName) {
console.log(userName + " " + "This is from Services")
return $http.get("https://api.github.com/users/" + userName);
};
return factory;
};
gitHubApiFactory.$inject = ['$http'];
angular.module('gitHubApp').factory('gitHubApiFactory',gitHubApiFactory);
}());
Below is gitHubApiController.js
(function() {
var gitHubInfoController = function ($scope,gitHubApiFactory) {
$scope.user = null;
$scope.gitHubUser = function(userName) {
gitHubApiFactory.getUserName(userName)
.success(function (data) {
$scope.user = data;
console.log(data);
})
.error(function(data, status, headers, config) {
$log.log(data.error + ' ' + status);
});
}
};
gitHubInfoController.$inject = ['$scope','gitHubApiFactory'];
angular.module('gitHubApp')
.controller('gitHubInfoController', gitHubInfoController);
}());
Below is userRepoInfo.html
<div data-ng-controller="gitHubInfoController">
<h1>Github App</h1>
<input type="text" id="gitUserName" ng-model="gitUser" placeholder="Please enter your GitHub Username">
Get my Repository
{{user.login}}
</div>
Below is app.js
(function() {
var app = angular.module('gitHubApp', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/', {
controller: 'gitHubInfoController',
templateUrl: 'app/views/userRepoInfo.html'
})
.otherwise( { redirectTo: '/' } );
});
}());
Below is index.html
<!doctype html>
<html data-ng-app="gitHubApp">
<head>
<title>Github Repository App</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div data-ng-view></div>
<script src="vendor/angular.js"></script>
<script src="vendor/angular-route.js"></script>
<script src="app/app.js"></script>
<script src="app/controllers/gitHubApiController.js"></script>
<script src="app/services/gitHubApiServices.js"></script>
</body>
</html>
Please help me out with this problem. I had spend couple of hours but no luck.
Thank you for your effort
I have tried your code with
{{user.login}}
instead of {{$scope.user.login}} in plinkr and it works fine. It returns my username (or any other info I request from GitHub RestFull Api.
You should not use $scope in the view. Angular wil lfigure out the proper scope for you and inject it to be used by the view.
Have a look at this plunkr: http://plnkr.co/edit/16yyngPoZBgzVvfyWCDq
P.S: I have flattened your folder structure for the sake of simplicity.
I'm new to Angular JS. Sorry for this simple question.
I have learnt something from this tutorial: http://courseware.codeschool.com/shaping-up-with-angular-js/Slides/level01-05.pdf
And I have tried an example. This is not working. http://jsfiddle.net/89wfv/1/
HTML:
<html ng-app="main">
<body>
<div ng-controller="con">
<div>{{con.desc}}</div>
<input type='button' ng-click='getDesc();' value='Get name' />
</div>
</body>
</html>
Script
(function() {
var app = angular.module("main", []);
app.controller("con", function() {
this.desc = "test description";
this.getDesc = function() {
alert(this.desc);
}
});
})();
Problem is showing description in div and alert description by click.
Thanks in advance.
you forgot controller as something
<div ng-controller="con as ctrl">
<div>{{ctrl.desc}}</div>
<input type='button' ng-click='ctrl.getDesc();' value='Get name' />
</div>
take a look at the guide instead :
https://docs.angularjs.org/guide/controller
works:
http://jsfiddle.net/pYh89/
you didnt load angular correctly and add several syntax errors.
var app = angular.module("main", []);
app.controller("con", function () {
this.name = 'foo';
this.getName = function () {
alert("foo");
};
});
Angular JS is missing in your code please include it after downloading it.
<script src="angular.js"></script>
You can also use online version.
You forgot different things:
Here's a corrected JSfiddle:
http://jsfiddle.net/89wfv/2/
You have to:
Use $scope instead of this to reference to the data that is to be bound to the view, eg:
app.controller("con", function($scope) {
$scope.name = 'vasu';
$scope.getName = function() {
alert();
}
});
Put the script tag in Head
Not use the html tag, that could be overwritten by JSfiddle:
Do rather something like this:
<div ng-app="main">
<div ng-controller="con">
</div>
</div>