console.log for $scope in angular js - javascript

Why I'm not able to console output $scope values ? I'm trying to extract user assigned values from the pages and retrieve in controller. Eventually i would like to pass this to service so multiple controllers can access these data.
HTML
<!DOCTYPE html>
<html lang="en-us" ng-app="myApp">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<meta charset="UTF-8">
<link rel="stylesheet" href="css/bootstrap.min.css" />
<!-- CDN lib files -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular-animate.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/1.1.0/ui-bootstrap-tpls.min.js"></script>
<!-- custom angular script -->
<script src="js/app.js"></script>
</head>
<body>
<div class="container">
<div ng-controller="mainController">
<h1>Hello world!</h1>
<label> Please enter something</label>
<input textarea ng-model="name"></input>
<h4> This is what you entered : {{ name }} </h4>
<h4 style=color:red> now filtering: {{ lower() }}</h4>
</div>
</div>
</body>
</html>
APP.JS
var myApp = angular.module('myApp', []);
myApp.controller('mainController', ['$scope', '$filter', function($scope, $filter) {
$scope.name = 'Test ';
$scope.lower = function(){
return $filter('lowercase')($scope.name);
}
$scope.name = $scope.lower();
console.log($scope.name);
console.log($scope.lower());
}]);
Console will output values upon initializing but not after user make changes.

You need to watch the scope variable:
$scope.$watch('name', function() {
console.log($scope.name);
});
More information: https://stackoverflow.com/a/15113029/5787736

Just a more "functional" version. Everyone is right, you are logging the observable, not what was observed. What you want is for console.log to be called on each change to $scope, not called once (as you have it now).
$scope.$watch("name", console.log);

You're logging only from the constructor. If you want to log each time something changes, consider a watch:
$scope.$watch("name", function() {
console.log($scope.name);
}

Why would you expect a controller to be rerendered when a scope variable changes? You can use scope watchers or input event listeners to listen for changes.
Here's an example with a watcher:
var myApp = angular.module('myApp', []);
myApp.controller('mainController', ['$scope', '$filter', function($scope, $filter) {
$scope.name = 'Test ';
$scope.lower = function(){
return $filter('lowercase')($scope.name);
}
$scope.name = $scope.lower();
console.log($scope.name);
console.log($scope.lower());
$scope.$watch('name', function() {
console.log($scope.name);
console.log($scope.lower());
});
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" class="container">
<div ng-controller="mainController">
<h1>Hello world!</h1>
<label>Please enter something</label>
<input textarea ng-model="name" />
<h4> This is what you entered : {{ name }} </h4>
<h4 style=color:red> now filtering: {{ lower() }}</h4>
</div>
</div>

Related

Getting an error in AngularJS

I am creating a small web app where I will show a chart of the top 10 popular TV shows. Then, When I go to the browser and inspect I get an error:
Error: [$injector:unpr] http://errors.angularjs.org/1.5.6/$injector/unpr?p0=showProvider%20%3C-%20show%20%3C-%20MainController
<!doctype html>
<html>
<head>
<link href='https://fonts.googleapis.com/css?family=Montserrat:400,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link href="css/main.css" rel="stylesheet" />
<!-- Angular JS -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<body ng-app="Top10App">
<div class="header">
<div class="container">
10
</div>
</div>
<div class="main" ng-controller="MainController">
<div class="container">
<div class="content">
<!--TODO: Loop through shows and display each one with this HTML-->
<!--ng-repeat="show in shows" -->
<div>
<div class="rank">{{$index + 1}}</div>
<h2 class="series"> {{ index.series }}</h2>
<p class="genre">{{ index.genre }} </p>
<p class="run-start"> {{ index.run_start }}</p>
<p class="description"> {{ index.description }} </p>
</div>
</div>
</div>
</div>
<!-- Modules -->
<script src="js/app.js"></script>
<!-- Controllers -->
<script src="js/controllers/MainController.js"></script>
<!-- Services -->
<script src="js/services/show.js"></script>
</body>
</html>
Javascript
MainController.js
app.controller('MainController', ['$scope', 'show', function ($scope, show) {
show.success(function(data) {
$scope.show = data;
});
}]);
show.js
app.factory('Top10App', ['$http', function($http){
return $http.get('shows.json')
.success(function(data){
return data;
})
.error(function(err){
return err;
});
}]);
You're defining your service name as 'Top10App', so that's the way you should access it, not by the file name.
['$scope', 'Top10App', function ($scope, Top10App) { ...
Top10App.success(...
First, do you created the module? You should has something like:
// app.js
angular.module('app', []);
// maincontroller.js
angular.module('app').controller('myController, ...', [.......]);
// factory.js
angular.module('app').factory(...)
You are trying to inject show as a dependency for your controller, but it doesn't look like that is defined anywhere. That's why your error is telling you that it's an unknown provider.
I'm guessing you're trying to use your Top10App factory, so you need to inject it as such
app.controller('MainController', ['$scope', 'Top10App', function ($scope, Top10App) {
Top10App.success(...)
}

Angularjs variable out of ng-view

I want to have particular variable for menu to know which class to be active. Up to now I know how to set variable inside ng-view but I want to keep my menu out of that view. If I set variable in function in controller isn't visible outside of ng-view and that is exactly what I want to, to be visible. I try with rootscoope but I couldn't manage. If someone can help me my code is like this:
index.html
<!DOCTYPE html>
<html lang="en" ng-app="example">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="libs/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="assets/css/font-awesome.min.css" rel="stylesheet">
<link href="assets/css/main.css" rel="stylesheet">
<title>Example</title>
</head>
<body>
<div class="container-fluid main-header">
<div class="main-menu-active">First page</div>
<div class="main-menu">Second page</div>
</div>
<div ng-view class="main-body"></div>
<script src="libs/jquery/dist/jquery.min.js"></script>
<script src="libs/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="libs/angular/angular.min.js"></script>
<script src="libs/angular-route/angular-route.min.js"></script>
<link href="libs/ng-dialog/css/ngDialog.min.css" rel="stylesheet">
<link href="libs/ng-dialog/css/ngDialog-theme-default.css" rel="stylesheet">
<script src="libs/ng-dialog/js/ngDialog.js"></script>
<script src="app/app.js"></script>
<script src="app/controllers/mainCtr.js"></script>
</body>
</html>
app.js
(function () {
'use strict';
angular
.module('example', ['ngRoute','ngDialog'])
.config(function ($routeProvider,$httpProvider) {
$routeProvider.when('/', {
controller: 'mainCtr',
controllerAs: 'mCtr',
templateUrl: 'app/views/firstPage.html'
});
$routeProvider.when('/second', {
controller: 'mainCtr',
controllerAs: 'mCtr',
templateUrl: 'app/views/secondPage.html'
});
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
}).run(function($http, $httpParamSerializerJQLike) {
//decode json on every submit form
$http.defaults.transformRequest.unshift($httpParamSerializerJQLike);
})
})();
controller:
(function() {
'use strict';
angular
.module('example')
.controller('mainCtr', mainCtr);
mainCtr.$inject = ['$window','$routeParams','ngDialog','$timeout'];
function mainCtr($window,$routeParams,ngDialog,$timeout) {
var vm = this;
vm.firstPage = firstPage;
vm.secondPage = secondPage;
function firstPage() {
vm.test = 'This is first page';
}
function secondPage() {
vm.test = 'This is second page';
}
}
})();
I want to have access to variable vm.test in <div class="container-fluid main-header">
I would make a Controller around the ng-view which hold the value(s):
<body ng-controller="OuterController">
<div class="container-fluid main-header">
<div class="main-menu-active">First page</div>
<div class="main-menu">Second page</div>
</div>
<div ng-view class="main-body"></div>
...
</body>
and if you want to share data between the controllers in ng-view directive use a service.
So I've made a plunker to illustrate, how data sharing is accomplished: https://plnkr.co/edit/axekEgrFwnm93aFXoMKd
So the basic idea is to use a service and in someway either by button click as in the question or automatically in contoller as plunker, set the shared value.
Service
app.service('commonInfomation', function() {
return {
test: ''
};
});
Inner controller
app.controller('FirstCtrl', function($scope, commonInfomation) {
commonInfomation.test = "Hello from first page";
});
Outer controller
app.controller('MainCtrl', function($scope, commonInfomation) {
$scope.commonInfomation = commonInfomation;
});
View
<body ng-controller="MainCtrl">
<h2>{{commonInfomation.test}}</h2>
<div class="container-fluid main-header">
<a href="#/">
<div class="main-menu-active">First page</div>
</a>
<a href="#/second">
<div class="main-menu">Second page</div>
</a>
</div>
<div ng-view class="main-body"></div>
</body>
Module
var app = angular.module('plunker', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'firstpage.html',
controller: 'FirstCtrl'
})
.when('/second', {
templateUrl: 'secondpage.html',
controller: 'SecondCtrl'
})
});

Cannot access http json service in angular js

I am new to angularjs and I want to know why it isn't working.
The code has a flaw and am not sure about the same.
Thinking from java perspective,httpController defined has nested function defined inside.
Here it is my code
index.html
<!DOCTYPE html>
<html >
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div ng-app="myapp" ng-controller="HelloController">
<h2>{{message}}</h2>
</div>
<div ng-app="httpService" ng-controller="httpController">
<div>FirstName:{{user.name}}</div>
</div>
</body>
</html>
Script.js
var app = angular.module("myapp", []);
app.controller("HelloController", function($scope) {
$scope.message = "Hello, AngularJS";
});
var httpApp=angular.module("httpService",[]);
httpApp.controller("httpController",function($scope,$http){
var onUserComplete=function(response){
$scope.user=""response.data"";
}
$http.get("https://api.github.com/users/rob").then(onUserComplete);
}
);
Only one ng-app will be automatically bootstrapped on your page. That's why if you remove the first ngApp directive, the second one will work.
var httpApp = angular.module("httpService", []);
httpApp.controller("httpController", function($scope, $http) {
var onUserComplete = function(response) {
$scope.user = response.data;
}
$http.get("https://api.github.com/users/rob").then(onUserComplete);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<div ng-app="httpService" ng-controller="httpController">
<div>FirstName: {{user.name}}</div>
</div>
NOTE: You have a typo in your callback, remove ""s around your response.data. Also, since you are using Angular 1.5.6, you don't need to specify dependencies/inject your $http service to make your code work.
https://plnkr.co/edit/LyWCLeBeyHPzjys3LOcr?p=preview
<body ng-app="httpService">
<div ng-controller="httpController">
<div>FirstName: {{user.key}}</div>
</div>
</body>
This link is working fine...just try it out
Do not use ng-app more than once in your program...Your code would not work

ng-click does not trigger the function associated with it?

I am having troubles with using ng-click. I have added ng-click directive to the button. It does not trigger the function associated with ng-click. In Angular Batarang tool, it says the functions are undefined.
I tried the problem in Plunker.It does work. And also If i hard code the file path it works.
index.html code
<!DOCTYPE html>
<HTML ng-app="myEventApp">
<head>
<meta charset="UTF-8">
</head>
<body>
<h1 ng-controller="HelloWorldController">{{ helloMessage }}</h1>
<div ng-controller="EventDetail">
</div>
<div ng-include="" src="fileName"></div>
<!--<ng-include src="fileName"></ng-include>-->
<!--<div ng-include="" src="'template/testing10000.html'"></div>-->
<button ng-click=incrementCounter()>Next</button>
<button ng-click=decrementCounter()>Back</button>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.js"></script>
<script src="js/app.js"> </script>
</body>
</HTML>
app.js code
var app = angular.module("myEventApp", []);
app.controller('HelloWorldController', ['$scope', function($scope){
$scope.helloMessage = "Book Viewer";
}]);
app.controller('EventDetail', ['$scope', function($scope){
$scope.counter = 0;
$scope.fileName = 'template/testing1000'+$scope.counter+'.html';
$scope.incrementCounter = function(){
$scope.counter++;
$scope.fileName = 'template/testing1000'+$scope.counter+'.html';
console.log($scope.counter);
}
$scope.decrementCounter = function(){
$scope.counter--;
$scope.fileName = 'template/testing1000'+$scope.counter+'.html';
console.log($scope.counter);
}
}]);
You declared the functions inside the EventDetail controller, but you have the buttons outside of the controller container in the html.
<div ng-controller="EventDetail">
<div ng-include="" src="fileName"></div>
<button ng-click="incrementCounter()">Next</button>
<button ng-click="decrementCounter()">Back</button>
</div>

Simple binding issue

Hi I am having trouble with this tutorial. I copied over the code but for some reason it is not working.
This is the html code
<!DOCTYPE html>
<html ng-app>
<head>
<title>Simple app</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.js">
</script>
</head>
<body>
<div ng-app="myApp">
<div ng-controller = "MyController">
<h1>{{ person }}</h1>
and their name:
<h2> {{person.name}}</h2>
</div>
</div>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
and here is the JS
var app = angular.module('app', []);
app.controller('MyController', function($scope) {
$scope.person = {
name: "Ari Lerner"
};
});
It doesn't look like the AngularJS code is being recognized. Any ideas?
Your app name in the module definition:
var app = angular.module('app', []);
doesn't match the one you reference in your dom:
<div ng-app="myApp">
Change your module definition to:
var app = angular.module('myApp', []);

Categories

Resources