How to retrieve the ng-model value to a controller in AngularJS - javascript

I have a simple view with an input text field in which the user enter his name and a controller must retrieve that value an assign to employeeDescription variable. The problem is that the ng-model value (from the input) doesn't come to the controller, I just tried using $watch like Radim Köhler explains Cannot get model value in controller method in angular js but doesn't work. I just think it must be simple.
Also a just try by retrieving the name variable (ng-model) from the $scope, like $scope.employeeDescription = $scope.name; but doesn't retrieve value and the Google chrome console doesn't give me any output about that. Any solution?
index.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
</head>
<body ng-app='angularApp'>
<div ng-controller='nameController'>
<div>
Name <input type="text" ng-model='name' />
</div>
Welcome {{employeeDescription}}
</div>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
app.js
(function(angular) {
var myAppModule = angular.module('angularApp', []);
myAppModule.controller('nameController', function($scope) {
$scope.employeeDescription = name;
});
})(window.angular);

Your code should fail, cause the 'name' variable in the controller is never defined. You have two variables defined in your code: $scope.employeeDescription and $scope.name (defined in the ng-model of the input). Note that '$scope.name' is being defined, not 'name'.
My suggestion is to leave only one variable:
<div>
Name <input type="text" ng-model='employeeDescription' />
</div>
myAppModule.controller('nameController', function($scope) {
$scope.$watch('employeeDescription', function() {
console.log($scope.employeeDescription);
});
});

Related

AngularJS error loading Controller

I have a really dumb problem but I don't know how to fix it. I have this index.html file with AngularJS loaded. I'm using Plunker to test the code:
<!DOCTYPE html>
<html ng-app="">
<head>
<script data-require="angular.js#1.4.8" data-semver="1.4.8" src="https://code.angularjs.org/1.4.8/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="BodyController">
<h1>{{ message }}</h1>
</body>
</html>
And this script.js file with this information:
var BodyController = function($scope) {
$scope.message = "Hi Angular!"
}
In the inspector it says:
Error: [ng:areq] Argument 'BodyController' is not a function, got undefined
The script is loaded. I have defined the controller in the JS file and attach the ng-controller directive, so I don't know where this can fail.
This is very basic of AngularJS.
You first need to create a module:
var fooApp = angular.module("foo", [])
And then, register your controller there:
var BodyController = function($scope) {
$scope.message = "Hi Angular!"
}
fooApp.controller("BodyController", BodyController);
And, in your HTML tag, change your ng-app like this:
<html ng-app="foo"></html>
You need to add the controller to your Angular module.
angular.module('app', [])
.controller('BodyController', function($scope) {
$scope.message = "Hi Angular!"
})
More info on how to setup a controller
https://docs.angularjs.org/guide/controller
In HTML, add
<html ng-app="myapp">
and the script is
angular.module('myapp', []).controller('BodyController',BodyController)
There were several errors
ng-app was not set
angular module was not defined
the controller was not defined
angular.module('app', [])
.controller('BodyController', function($scope) {
$scope.message = "Hi Angular!"
});
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body ng-controller="BodyController">
<h1>{{ message }}</h1>
</body>
</html>

Beginners help to Angular JS debugging via console errors

AngularJS is new to me (and difficult). So I would like to learn how to debug.
Currently I'm following a course and messed something up. Would like to know how to interpret the console error and solve the bug.
plnkr.co code
index.html
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="MainController">
<h1>{{message}}</h1>
{{ username }}
<form action="searchUser" ng-submit="search(username)">
<input type="search"
required placeholder="Username to find"
ng-model="username"/>
<input type="submit" value="search">
</form>
<div>
<p>Username found: {{user.name + error}}</p>
<img ng-src="http://www.gravatar.com/avatar/{{user.gravatar_id}}" title="{{user.name}}"/>
</div>
</body>
</html>
script.js
(function() {
var app = angular.module("githubViewer", []);
var MainController = function($scope, $http) {
var onUserComplete = function(response) {
$scope.user = response.data;
};
var onError = function(reason) {
$scope.error = "could not fetch data";
};
$scope.search = function(username) {
$http.get("https://api.github.com/users/" + username)
.then(onUserComplete, onError);
};
$scope.username = "angular";
$scope.message = "GitHub Viewer"; };
app.controller("MainController", MainController);
}());
The console only says
searchUser:1 GET http://run.plnkr.co/lZX5It1qGRq2JGHL/searchUser? 404
(Not Found)
Any help would be appreciated.
In your form, action you have written this
<form action="searchUser"
What this does is it will try to submit to a url with currentHostName\searchUser, so in this case your are testing on plunker hence the plunker url.
You can change the url where the form is submitted. Incase you want to search ajax wise then you dont even need to specify the action part. You can let your service/factory make that call for you.
Though not exactly related to debugging this particular error, there is a chrome extension "ng-inspector" which is very useful for angularJS newbies. You can view the value each of your angular variable scopewise and their value. Hope it helps!
Here is the link of the chrome extension: https://chrome.google.com/webstore/detail/ng-inspector-for-angularj/aadgmnobpdmgmigaicncghmmoeflnamj?hl=en
Since you are using ng-submit page is being redirected before the response arrives and you provided any action URL as searchUser which is not a state or any html file so it being used to unknown address, it is async call so it will take some time you can use input types as button instead of submit.
Here is the working plunker.
<!DOCTYPE html>
<html ng-app="githubViewer">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="MainController">
<h1>{{message}}</h1>
{{ username }}
<form >
<input type="search"
required placeholder="Username to find"
ng-model="username"/>
<input type="button" ng-click="search(username)" value="search">
</form>
<div>
<p>Username found: {{user.name + error}} {{user}}</p>
<img ng-src="http://www.gravatar.com/avatar/{{user.gravatar_id}}" title="{{user.name}}"/>
</div>
</body>
</html>

Calling an AngularJS controller function from outside of it

I have the following code:
app.controller('MatrixExpertCtrl', function($scope,$http){
$scope.PassedMatrix=[];
$scope.GetMatrixFromServer=function(){
$http.get("http://localhost:3000/getmatrixfromdb").success(function(resp){
alert("The matrix grabbed from the server is: " + resp[0].ans);
$scope.PassedMatrix.push(resp[0].ans);
});
};
$scope.DispSize=function(){
alert("testing");
alert("The size is "+$scope.PassedMatrix[0].size) ;
};
//$scope.GetMatrixFromServer();
});
Now, suppose, in HTML, I have something like this:
<div class="col-sm-3 col-md-3 col-lg-3">
<div class="text-center">
<h3>Example Survey</h3>
<p>example paragrah</p>
<p>More random text</p>
<p>ending the paragraphs</p>
<button id="updmat" ng-click="DispSize();" type="button" class="btn btn-default">Updates</button>
</div>
//Much more code
<div id="body2">
<div class="col-sm-6 col-md-6 col-lg-6" style="background-color:#ecf0f1;">
<div ng-controller="MatrixExpertCtrl" ng-app="app" data-ng-init="GetMatrixFromServer()">
<div class="text-center">
Meaning with this:
Is it possible to call a function that is defined inside a controller, from outside of the scope of that same controller?
I need this because the function is manipulating a shared object, owned by the controller in a very very simple fashion (for example, clicking on the button changes the color of a given element).
I am having trouble to make this work, any help will be appreciated.
I think that declaring some data structures as global would help me solving this problem, but, I would like to avoid doing that because, besides it being bad practice, it might bring me more problems in the future.
If i understand your problem correctly than what you basically do have is one utility function which will work on your shared object and do your useful things (i.e. clicking on the button changes the color of a given element) and now you do require the same behaviour in another controller outside of it's scope. You can achieve the same thing in 2 different ways :
1).Create a service and make it available in your controllers like this :
<!doctype html>
<html ng-app="myApp">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.factory('myService', function() {
return {
changeColour: function() {
alert("Changing the colour to green!");
}
};
});
myApp.controller('MainCtrl', ['$scope', 'myService', function($scope,
myService) {
$scope.callChangeColour = function() {
myService.changeColour();
}
}]);
</script>
</head>
<body ng-controller="MainCtrl">
<button ng-click="callChangeColour()">Call ChangeColour</button>
</body>
</html>
Pros&Cons: More angularistic way, but overhead to add dependency in every different controllers and adding methods accordingly.
2).Access it via rootscope
<!doctype html>
<html ng-app="myApp">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.run(function($rootScope) {
$rootScope.globalChangeColour = function() {
alert("Changing the colour to green!");
};
});
myApp.controller('MainCtrl', ['$scope', function($scope){
}]);
</script>
</head>
<body ng-controller="MainCtrl">
<button ng-click="globalChangeColour()">Call global changing colour</button>
</body>
</html>
Pros&Cons: In this way, all of your templates can call your method without having to pass it to the template from the controller. polluting Root scope if there are lots of such methods.
try removing semicolon
ng-click="DispSize()"
because it binds ng-click directive to the function.

binding not working in nested controller

I'm new to Angular JS.
I have a few questions. Scope seems to be working with my first controller testController but not with my second controller controlspicy.
Why is not letting me print out $scope.greeting ? Shouldn't the binding work because I assigned a controller.
Here's a plunkr link which directs straight to the code.
http://plnkr.co/edit/NbED8vXNiZCqBjobrISa?p=preview
<!DOCTYPE html>
<html ng-app="newtest">
<head>
<script data-require="angular.js#*" data-semver="1.3.5" src="https://code.angularjs.org/1.3.5/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
<script src="spicy.js"></script>
</head>
<body ng-controller="testController">
<h1>Hello Plunker! {{message}}</h1>
<input type="text" name="firstName" ng-model="thetext">
{{double(thetext)}}
<h1 ng-controller="controlspicy">new test</h1>
<h2>{{greeting}}</h2>
</body>
</html>
script.js
var app = angular.module("newtest", [])
.controller("testController", ["$scope", function($scope) {
$scope.message = "hola";
$scope.double = function(value){
if (value == null){
return 0;
}
return value*2;
};
}]);
spicy.js
var appl = angular.module("thespicy", [])
.controller("controlspicy", ["$scope", function($scope){
$scope.greeting = "hello";
}]);
As previously mentioned by Preston you need to wrap the <h2> inside a tag with ng-controller. There is one more issue however.
controlspicy is defined in another module than the one you specify in ng-app.
Change angular.module("thespicy", []) in spicy.js to angular.module("newtest").
You should almost never use more than one module in one app. You could however divide it into different sub-modules but if your new to Angular I would recommend using just one module to start with.
To clarify; you should only define a module once by typing angular.module("module_name", []). Notice the [] here. In this array you would put dependencies for the module (if you really wanted the 'thespicy' module you could have included it as a dependency with angular.module("newtest", ['thespicy']). If you later wanted to add a controller to the module you would reference the module with angular.module("module_name") (no []). For example:
// Define a module
angular.module('foo', []);
// Reference the previously defined module 'foo'
angular.module('foo')
.controller('barCtrl', function() { ... });
Here is a working fork of your example: http://plnkr.co/edit/rtUJGeD52ZoatoL3JgwY?p=preview btw.
The nested controller only controls inside the scope of the tag. In this case, it only has access to the scope inside of the h1 tag.
Try this:
<!DOCTYPE html>
<html ng-app="newtest">
<head>
<script data-require="angular.js#*" data-semver="1.3.5" src="https://code.angularjs.org/1.3.5/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
<script src="spicy.js"></script>
</head>
<body ng-controller="testController">
<h1>Hello Plunker! {{message}}</h1>
<input type="text" name="firstName" ng-model="thetext">
{{double(thetext)}}
<div ng-controller="controlspicy">
<h1>new test</h1>
<h2>{{greeting}}</h2>
</div>
</body>
</html>
Here's a working plunker of your example: http://plnkr.co/edit/gufbBI4i68MGu8FWVfJv?p=preview
I should point out that you didn't include your controller in your main app.
script.js should start like this:
var app = angular.module("newtest", ['thespicy'])
You have multiple apps
check this plunkr for working nested controllers
<div>
<div ng-controller="testController">
<h1>Hello Plunker! {{message}}</h1>
<input type="text" name="firstName" ng-model="thetext">
{{double(thetext)}}
</div>
<div ng-controller="thespicy">new test
<h2>{{greeting}}</h2>
</div>
</div>
script.js
var app = angular.module("newtest", [])
.controller("testController", ["$scope", function($scope) {
$scope.message = "hola";
$scope.double = function(value){
if (value == null){
return 0;
}
return value*2;
};
}])
.controller('thespicy', ["$scope", function($scope) {
$scope.greeting = "Hello";
}])

In angularjs, calling controller as constructor is not working

i am new to angularjs and i tried practicing some examples. In the below stated example I am trying to initialize a value and setting it in scope. it is working fine, if i initialize the controller and scope values as given in the commented lines . but instead of those commented lines of code, if i try to set a controller and initialize scope value , like a regular javascript constructor function, then my example is not working.. Please anyone kindly explain why it is not working ?
<html>
<head>
<title>My Practices</title>
<script type="text/javascript" src="lib/angular.min.js"></script>
<script type="text/javascript">
/*var myApp = angular.module('myApp', []);
myApp.controller('HelloController', ['$scope', function($scope){
$scope.value = "World";
}]);*/
var HelloController = function ($scope) {
$scope.value = 'World';
}
</script>
</head>
<body ng-app>
<div ng-controller="HelloController">
<input type="text" ng-model="value" placeholder="enter your name">
<div>Hi {{value}} !! </div> </div>
</body>
</html>

Categories