In angularjs, calling controller as constructor is not working - javascript

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>

Related

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";
}])

Angular JS not working in plunker

I couldn't get my angular code to run in plunker. I have attached the details. Could any of you help me out? Basically it's a problem with ngcontroller I guess but I am not sure.
<!DOCTYPE html>
<html ng-app>
<head>
<script data-require="angular.js#*" data-semver="1.3.15" src="https://code.angularjs.org/1.3.15/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="MainController">
{{ 5 / 2 }}<br>
{{message}}
</body>
</html>
Contents of javascript script.js file
var MainController = function($scope){
$scope.message = "Welcome!";
};
Plunk
http://plnkr.co/edit/mzgdELALCP7DN2ikJHsC?p=preview
In version 1.3.*, you cannot longer declare a global controller function.
Instead define a module, and use your controller function:
var SidController = function($scope){
$scope.message = "WElcome.";
};
SidController.$inject = ['$scope'];
angular.module('app', []).controller('SidController', SidController);
In your html
<html ng-app="app">
See this plunker.
I had the same issue.. Well done on starting a tutorial! Simply replace the script in your index.html with
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>
I suppose the library Plunker currently has is outdated or something.
Working Plunkr (with a different AngularJS version. #user3906922 has a better answer, where your version stays the same).
Use this for HTML for instance:
<!doctype html>
<html ng-app>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-controller="SidController">
<h1>Hello Plunker!</h1>
{{ 5 / 2 }}<br>
{{message}}
</div>
</body>
</html>
Check this plunkr
You need to define your module and then register the controller
http://plnkr.co/edit/9zAV5nSWH05FYscEWYZ5?p=preview
angular.module( 'demoApp', []);
angular.module( 'demoApp' )
.controller( 'SidController', function($scope){
$scope.message = "WElcome.";
});
You should create your module.
angular.module('app', []).controller("SidController", function($scope) {
$scope.message = "WElcome.";
});
Then in your html element, set your attribute like this:
ng-app="app"

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

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);
});
});

Error in Angular JS

I included angular js in my asp.net mvc project but when i call object in controller
the angular js expressions do not evaluate
here is the app.js code please suggest
var app = angular.module('app', []);
app.controller('createController', createController);
and here is the createController code
var createController = function ($scope) {
$scope.mydata = 'I work!';
}
here is what i include in html
<html ng-app="app">
<script src="~/Scripts/angular.min.js"></script>
<script src="~/appAjs/app.js"></script>
<script src="~/appAjs/controllers/createController.js"></script>
<div ng-controller="createController">
{{scope.mydata}}
{{6+9}}
from your code, I can only suspect two things
your javascript does not have the proper scope
do not use the word scope in your "scope" code
first part: javascript scope:
Always use an IIFE, in your case your code should look like:
(function(){
var app = angular.module('app', []);
var createController = function ($scope) {
$scope.mydata = 'I work!';
};
app.controller('createController', createController);
}());
second part: don't use the word scope
in your HTML, you should not use the word scope as it's already inherit in your controller as that's the model you are passing to the "view"
hence, your code should look like:
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div ng-controller="createController">
{{mydata}}
{{6+9}}
</div>
</body>
</html>
the result is:
I work! 15
live code in JSBIN so you can check it out.
your HTML page, all together should look like this:
if you have only one file
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="utf-8">
<title>My AngularJs App</title>
</head>
<body>
<!-- HTML -->
<div ng-controller="createController">
{{mydata}}
{{6+9}}
</div>
<!-- AngularJS required -->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
<!-- AngularJS code -->
<script>
(function(){
var app = angular.module('app', []);
var createController = function ($scope) {
$scope.mydata = 'I work!';
};
app.controller('createController', createController);
}());
</script>
</body>
</html>
if you're using 2 files
file index.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="utf-8">
<title>My AngularJs App</title>
</head>
<body>
<!-- HTML -->
<div ng-controller="createController">
{{mydata}}
{{6+9}}
</div>
<!-- AngularJS required -->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
<!-- AngularJS extra files -->
<script src="createController.js"></script>
</body>
</html>
file createController.js (in the same folder as index.html)
(function(){
var app = angular.module('app', []);
var createController = function ($scope) {
$scope.mydata = 'I work!';
};
app.controller('createController', createController);
}());
I think the problem may well be the order in which you are including your scripts:
Try the following:
<script src="~/Scripts/angular.min.js"></script>
<script src="~/appAjs/controllers/createController.js"></script>
<script src="~/appAjs/app.js"></script>
Reasoning is that app.js tries to define a controller using a function that has not been defined when the function is run.
Points that {{scope.data}} should be {{data}} are correct, but do not explain {{6+9}} not working.
You need to create the controller in the context of the app module.
Your app.js should just have
angular.module('app', []);
and your createController code should look similar to this
angular.module('app')
.controller('createController', function ($scope) {
$scope.mydata = 'I work!';
});
You need to change the expression from
{{scope.mydata}}
to
{{mydata}}
Expression have access to scope and no keyword is required to access a scope object.

Categories