I have just started learning Angular js from w3school.com.
I have a simple question about controller.
As this is my code.
<html>
<body>
<div ng-app="" ng-Controller="HomeController">
<p> {{person.lname}}</p>
<p>First Name = <span ng-bind="person.fname"></span></p>
<p>Enter Details</p>
<p>First Name : <input type="text" ng-model="person.fname"/></p>
<p>Last Name : <input type="text" ng-model="person.lname"/></p>
<p>Middle Name : <input type="text" ng-model="person.mname"/></p>
</div>
</body>
<script src="angular.min.js"></script>
<script>
function HomeController($scope)
{
$scope.person={
fname:'Amit',
lname:'Kumar',
mname:'Verma'
}
}
</script>
</html>
As you can see i have used controller for binding the values.
as soon as i change the value of textbox , it reflect in p tag.
means it called the Homecontroller , but it doesn't calling that controller. i have checked by setting debug point in firbug. It should call the homeController.
As i am new , so it might be a simple question.
As stated by Yoshi, please read the official guide for a better start. They provide tutorials there and then you can start looking from other sources.
To answer your question, the controller HomeController is not actually being called each time a change has been done to its models. Controllers provide a way to group models and functions inside a scope. Inside the controller, you can add functions which can be triggered in your view.
Here is a fiddle that shows your controller with a model and a function inside.
// model
$scope.person = {
fname: 'Amit',
lname: 'Kumar',
mname: 'Verma'
}
// function
$scope.resetNames = function() {
console.log('I am called!');
$scope.person.fname = 'Amit';
$scope.person.lname = 'Kumar';
$scope.person.mname = 'Verma';
}
Good luck with your learning!
Please read Official AngularJS doc on controllers and how they work.
You have probably misunderstood how they work and thus expecting a different result. It is also advised to follow the Official doc guidelines and do the following:
var myApp = angular.module('myApp',[]);
myApp.controller('HomeController', ['$scope', function($scope) {
$scope.person={
fname:'Amit',
lname:'Kumar',
mname:'Verma'
}
}]);
Here's a working fiddle too:
http://jsfiddle.net/hpeinar/LxyL8e5k/
As of angular 1.3, global controller functions are no longer supported.
You should register your controllers in the following way:
app.controller('HomeController', HomeController);
Related
ng-if is not working when I change the values through simple javascript function.My function is getting called but the changes in values cannot be seen in view. Please refer below code.
HTML
<div id="span" ng-app='MyModule' ng-cloak ng-controller="MyController">
<div ng-if="!bool">
This is for true
</div>
<div ng-if="bool">
This is False
</div>
{{bool}}
<br>
<input type="submit" ng-click = "myfunction('test')" value="ng-if button">
</div>
<input type="submit" onClick = "check1()" value="simple JS button">
JS
angular.module('MyModule', [])
.controller('MyController', function ($scope) {
$scope.bool = true;
$scope.myfunction = function (data) {
$scope.bool = !$scope.bool;
};
});
function check1() {
angular.element(document.getElementById('span')).scope().myfunction('test');
}
When I use ng-click button it changes value of bool changes, but same doesn't happens with simple JS button . Actually I am implementing Angular in a page that already uses jQuery, so I need to use simple JS button.
JS Fiddle : JS Fiddle
At first, ng-click is able to parse an angular expression.
Second, it handles the reference to the current scope and performs a call to $scope.$apply to notify any watchers to update. If you would add a call to angular.element(document.getElementById('span')).scope().$apply() in your function, it should work as expected.
Use $scope.apply . This is because angulars digest cycle will not know if your value changes outside of its scope like in a simple JS function.
I want to show messages to the end user, just like Google, at the top center of the web panel.
I don't want to include the HTML and related script everywhere in every form and list and chart that I have. I want to centralize this messaging functionality into a service (in Angular JS term) that can be used everywhere.
And just like Google, I want to be able to show rich text in my messages, that is, I want to include links and probably other HTML stuff there. For example instead of showing Customer is defined, I want to show Customer is defined, <a href='#/customer/addPhone'>Now add a phone</a> to guide the user.
What I've done is to place the messages HTML in the root layout of my single paged application:
<div class="appMessages">
<span ng-show="message" ng-click="clearMessage()" ng-bind-html="message"></span>
</div>
and in our controllers, we inject the $rootScope and try to set the message property on it.
Yet I get no results. Can you guide me please?
As a general best practice I would avoid using $rootScope to pass the messages but rather use a dedicated service to update the message,
On your case the problem might be that you need to use angular $sce service to mark your html as trusted.
or load ng-santizemodule instead (which is a seperate module you need to load see offical doc)
That is needed because angular security requires you to explicitly check the html, if the source of your messages are from your code only, and not users inupts you can use the trustAsHtml as you know for sure it a safe html.
On your controller inject $sce, and bind it to your scope, and then use the $sce.trustAsHtml(value) function.
<div class="appMessages">
<span ng-show="message" ng-click="clearMessage()" ng-bind-html="$sce.trustAsHtml(message)"></span>
</div>
angular.module('app', [])
.component('message', {
controller: function($sce, messagService){
this.messagService = messagService;
this.$sce = $sce;
},
template: '{{$ctrl.message}}<div ng-bind-html="$ctrl.$sce.trustAsHtml($ctrl.messagService.message)"></div>'
})
.service('messagService', function(){
this.message = '';
this.updateMessage = function(message){
this.message = message;
}
})
.controller('mainCtrl', function($scope, messagService){
$scope.updateMessage = function () {
messagService.updateMessage('wow <b style="color:yellow;">shiny</b> message');
};
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<div ng-controller="mainCtrl" ng-app="app">
<message></message>
<button type="button" ng-click="updateMessage()"> update message</button>
</div>
In my index.html file, I have created a very bare-bones form. I have separated much of the detail into app.js so that if someone wants to have their version of the form look different, they just have to insert a modified copy of app.js (trying to go for portability here).
However, I am very new to AngularJS, which is what a lot of app.js is using. I could use some help please!
Here is a code snippet that I'm having some trouble with:
<body ng-controller="controller">
<div class="page">
<section class="signin">
<form name="form" novalidate>
<div class="intro">
<label ng-model="service-desk-name"></label>
<span ng-bind="service-desk-name"></span>
<label ng-model="welcome"></label>
<span ng-bind="welcome"></span>
</div>
Coupled with:
var app = angular.module('app',[]);
app.controller('controller', ['$scope', function($scope) {
$scope.service-desk-name = 'Arbitrary Service Desk Name';
$scope.welcome =
'Please sign in and a consultant will be with you shortly.';
}]);
Because I may be doing something dreadfully wrong, I'll explain what I want to do. The intro section is displayed above the actual form, showing the service desk name, and some kind of custom welcome or informational message through ng-model="service-desk-name" and ng-model="welcome", respectively. My hope is that I can get the HTML to grab value of these two models that I define in app.js. This way, the HTML doesn't control what is displayed, it just grabs what is defined and displays it.
Right now, these fields are not showing up at all on the webpage, indicating that there's just some kind of syntax error. I'm so new to Angular so I don't really know what to try to fix it from here.
replace
<label ng-model="service-desk-name"></label>
with
<label>{{service-desk-name}}</label>
ng-model means that you want bi-directional binding, and is used for example with inputs, so that when you start typing into the input, the value is stored inside anything that you reference through ng-model, i.e.
<input type="text" ng-model="inputValue" />
will save the input into $scope.inputValue
{{}} means you want to output something from the controller in the view.
Variable name can not have most special character (except _, $) when you are defining directly after a .(dot). This is the reason where controller code is throwing an error, since nothing is getting rendered on page.
You could define that property by specifying key over $scope object like
$scope['service-desk-name'] = 'Arbitrary Service Desk Name';
Additionally the ng-model would work on input element only, but you are using over label. Do below change to welcome as well.
<input ng-model="service-desk-name"/>
But Ideally you shouldn't be define scope variable in such format.
Preferred way would be to use camelCase while defining variables.
Agree with Pankaj Parkar
Also you can't get value in this case because you don't set "ng-app"
plnkr link
var app = angular.module('app', []);
app.controller('myController', function ($scope) {
$scope.serviceDeskName = 'Arbitrary Service Desk Name';
$scope.welcome = 'Please sign in and a consultant will be with you shortly.';
});
<!DOCTYPE html>
<html ng-app="app"> <!-- For example define your app module name here -->
<head>
<link rel="stylesheet" href="style.css">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="myController">
<div class="page">
<section class="signin">
<form name="form" novalidate>
<div class="intro">
<label ng-model="serviceDeskName"></label>
<span ng-bind="serviceDeskName"></span>
<hr>
<label ng-model="welcome"></label>
<span ng-bind="welcome"></span>
</div>
</form>
</section>
</div>
</body>
</html>
I did a very little application, but binding not working as model to object. How is it possible?
angular.module("simpleapp", [])
.controller("Controller", ['$scope', function($scope) {
$scope.sample = {};
$scope.sample.input = 4;
}]);
<body ng-app = "simpleapp" >
<input ng-model="sample.input" type="text" value="text" />
<div ng-controller = "Controller"><p>input "{{sample.input}}"</p></div>
</body>
You are using simpleapp in HTML and just app in your JS.
They have to be the same in order to work correctly.
Plus you put the input with the scope variable outside the controller. It should be inside.
For example you can edit your html like this:
<body ng-app="app" ng-controller="Controller">
<!-- other divs here -->
</body>
You have to update your body tag from <body ng-app="app"> and then you have put put your input inside the scope of your controller
<body ng-app="app">
<div ng-controller = "Controller">
<input ng-model="sample.input" type="text" value="text" />
<p>input "{{sample.input}}"</p>
</div>
</body>
The answers by Atul,NV Prasad and fbid are absolutely correct.You can view the DEMO here.
One thing that they have missed out is another way to bind your elements to the angular variable.That is using ng-bind.It is used as follows:
<p ng-bind="sample.input"></p>
What's the difference between ng-bind="sample.input" and
{{sample.input}}?
When you load the page, with the {{}} notation, you will see the curly brackets until the angular content is rendered.In the case of ng-bind, you won't.
For more details:LINK and this answer specifically
Use Proper Angularjs Version Library .You need to Go through Angularjs Doucmentation and Try to Understand by experimenting . That Makes you Strong
Some Beginner Mistakes :-
You Should write all the code after assigning Controller to Html
Element . Otherwise Your Code Don't Work even if it is Correct . You need
to assign a variable to Use.
html Code sample (understand Your mistake by taking look at code or the Below Plunkers :-) :-
<body ng-controller = "sampleController">
<input ng-model="sample.node" type="text" />
<p>input "{{sample.node}}"</p>
<input ng-model="sample1" type="text" />
<p>input "{{sample1}}"</p>
</body>
Controller Coding :-
angular.module("sampleApp", [])
.controller("sampleController", ['$scope', function($scope) {
$scope.sample = {'node':1};
$scope.sample1 = 'my first default value';
}]);
Here we go Simple Binding Example :-
http://jsfiddle.net/cmckeachie/Y8Jg6/
Plunker With Little More Concept of Data binding :-
https://plnkr.co/edit/TmAsSCKQDHfXYEbCGiHW?p=preview
Go through Documentation for some more understanding Good Luck !!
This seems like it should be easy to do, but I am not sure why this isn't working. All I want to do is pass this string to the function.
I've tried this.
<form ng-submit="edit(type)" ng-init="type='debt'">
I've tried this as well.
<div ng-controller="FormCtrl">
<form ng-submit="edit('debt')">
<input type="submit" value="ADD">
</form>
</div>
and on the js side.
app.controller('FormCtrl', function ($scope, $cookies, $http){
$scope.edit = function(typ){
alert(typ);
}
});
All I want to do is alert out that word 'debt'. All I get is undefined.
All of you code is working fine, as you included $cookies dependency without having angular-cookies.js included in your app (module name ngCookies), it was breaking your page. Eiether you want $cookies there then add the respective reference. Or remove that $cookies reference.
Working Plunkr