I have many elements in my HTML code that have their ngModel assignment defined as ng-model = "object.[something]".
For example:
<div class="form-group row" ng-model="object.askUser">
I do this to be clear of my purpose for these elements. My question is how do I access these element in my Javascript? Do I call $scope.object.askUser, $object.askUser, or something else? I had a hard time finding things on the web about this, most likely because I wasn't quite sure of the words to use in the search bar to describe what I am trying to do.
Inside your controller use $scope.object.askUser:
var app = angular.module('TestApp', []);
app.controller("testCtrl", function ($scope) {
$scope.someObject = {};
$scope.someObject.askUser = "Hello, world!";
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="TestApp">
<div ng-controller="testCtrl">
<input ng-model="someObject.askUser" />
</div>
</div>
Side note:
You use in your example <div> with ngModel.
ngModel Docs:
The ngModel directive binds an input,select, textarea (or custom form
control) to a property on the scope
If you want to one-way bind a model to a div use Angular Expression:
<div class="form-group row">
{{ object.askUser }}
</div>
Related
I am building a drum machine using AngularJS and having issues adjusting the tempo from the user interface.
I have got the object "this.tempo=120" & "<input class="bpm-input" type="number" onchange="updateBPM()" min="100" max="150" ng-model="$ctrl.tempo"></input>"
This doesn't seem to update the tempo value, only the value shown in the input box.
What function would I need to update the value within the controller?
It is normal, when you use AngularJS, you need to use the Angular WAY.
In other words, what angular do for you is the only way to do it.
AngularJS drastically control your DOM and use it as a copy.
If you change the DOM without the angular behavior, angular cannot update his copy and throws bad behaviors.
You need to use all Angular things, to tell him to apply his magic on your DOM.
Change your onclick attribute by ng-click angular directive, put your updateBPM into your controller scope, and this will works.
Hope that helps you!
Basic things you can do are as in the attached snippet also try having Angular patterns for a manageable code base and good performance Patterns
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myController as myCtrl">
<input class="bpm-input" type="number" ng-change="myCtrl.updateBPM()" min="100" max="150" ng-model="myCtrl.tempo"></input>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myController', function($scope) {
var myCtrl = this;
myCtrl.tempo=120;
myCtrl.updateBPM = function(){
alert(myCtrl.tempo);
}
});
</script>
</body>
</html>
Code is attached below
<script>
var mainModule = angular.module('mainModule', [])
.controller('mainCntrl', function($scope) {
var vm = this;
vm.tempo = 120;
});
</script>
<div ng-app="mainModule">
<div ng-controller="mainCntrl as ctrl">
<input class="bpm-input" type="number" min="100" max="150" ng-model="ctrl.tempo"></input>
</div>
</div>
{{}} is working fine but ng-model is not, at the same place.
I am using the following html-
<body ng-app="crud">
Gray input fields will not be visible.
<div ng-controller="ctrl">
<input type="text" value="sdf" ng-model="asdf"/>
<h1 ng-model="asdf"></h1> <!-- this doesn't work-->
<h1>{{asdf}}</h1> <!-- this work-->
</div>
</div>
</body>
asdf is defined in this js app like this
var app = angular.module("crud", []);
app.controller("ctrl", ['$scope', function($scope) {
$scope.asdf="ankur";
}]);
Can someone explain why is it so ?
The ng-model directive is to be used on the input fields such as input, select for two way data binding and to get an input from a user.
Where as the one way data binding expression {{}} or ng-bind directive is used to output the data in the view.
var app = angular.module("crud", []);
app.controller("ctrl", ['$scope', function($scope) {
$scope.asdf="ankur";
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="crud">
Gray input fields will not be visible.
<div ng-controller="ctrl">
<input type="text" value="sdf" ng-model="asdf"/>
<h1 ng-bind="asdf"></h1>
<h1>{{asdf}}</h1>
</div>
</div>
Use ng-bind for display purposes, instead of ng-model.
<h1 ng-bind="asdf"></h1>
You only want to use ng-model when binding to an element that will be editing the variable, such as a text field.
From documentation:
The ngModel directive binds an input, select, textarea (or custom form control) to a property on the scope using NgModelController, which is created and exposed by this directive.
You are trying to use it on a <h1>. Use ng-bind instead.
According the doc
the ngModel directive binds an input,select, textarea (or custom form control) to a property on the scope using NgModelController, which is created and exposed by this directive.
so you will not use it for display an H1
For the brackets they will be dirty checked and refreshed in every $digest, even if it's not necessary. So it's slower. Plus thez may appear while your angularjs is bootstrapping
ng-model : This directive binds the values of AngularJS application data to HTML input controls.
{{}} This use For Printing purpose only. you can put expression also like {{2*2}} it prints 4
Refer This for study basic syntax https://angularjs.org/
Can I use ng-model to build up an object over several views?
For instance, say in view1 I have
<input ng-model='myObject.firstName'>
And in view2 I have
<input ng-model='myObject.lastName'>
And in view3 I have
<input ng-model='myObject.email'>
The idea being you could hit a submit button in the last view, and return the object somewhere.
My initial approach to this is to have a service which declares an empty object, then have functions in the service which allow the controllers using the service to add their view input to that object, then return the object.
However I feel like this is quite a roundabout way of doing it!
If anyone could point me in the right direction I would really appreciate it.
You can use a service for that. Here an example with 3 controllers sharing the same object using 3 directives ng-model. Each controller modify the tested.value property, but you can use differents properties of course.
angular.module('test', []).factory('tested', function() {
return {
value : '123'
};
}).controller('ctrl1', function($scope, tested) {
$scope.tested = tested;
}).controller('ctrl2', function($scope, tested) {
$scope.tested = tested;
}).controller('ctrl3', function($scope, tested) {
$scope.tested = tested;
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="test">
<div ng-controller="ctrl1">
<input type="text" ng-model="tested.value" />
{{ tested.value }}
</div>
<div ng-controller="ctrl2">
<input type="text" ng-model="tested.value" />
{{ tested.value }}
</div>
<div ng-controller="ctrl3">
<input type="text" ng-model="tested.value" />
{{ tested.value }}
</div>
</div>
Since each view has its controller, the only way to share data is with a service of type "provider", "service" or "factory".
You could then modify your object from each controller with the methods you talk about.
In the end, to notify each view something changed, the service methods could raise an event from the service :
$rootScope.$broadcast('somethingChanged', myObject);
And each controller could listen with:
$scope.$on('somethingChanged', function(data) {
});
I'm new to Angular JS and am having trouble with custom directives. I've tried to copy a tutorial and I can't get it working using my own code.
Here's the relevant part of my HTML:
<div ng-controller="calcController" class="container">
<div class="form-group">
<label for="balInput">Balance:</label>
<input id="balInput" type="text" class="form-control" ng-model="balance" ng-change="updateAnnualInt(balance)" placeholder="Please enter your balance here...">
</div>
<p>{{'At a '+(interestRate)+'% interest rate you would save...'}}</p>
<p style="text-indent: 30px;" ng-repeat="interest in interests">{{'per '+interest.time+': '}}{{(interest.factor*annualInterest*0.01) | currency:'£'}}</p>
To start with, I'm just trying to turn the last paragraph into a custom directive. Here's my attempt:
app.directive('interest-amount',function(){
var directive={};
directive.restrict='E';
directive.template="<p style='text-indent: 30px;'>'per '+{{interest.time}}+': '{{(interest.factor*annualInterest*0.01) | currency:'£'}}</p>";
directive.compile=function(element,attributes){
var linkFunction=function($scope, element,attributes){
element.html("<p style='text-indent: 30px;'>per "+$scope.interest.time+": "+($scope.interest.factor*$scope.annualInterest*0.01)+"</p>");
}
return linkFunction;
}
return directive;
})
This isn't giving the HTML template I expect when I insert it as follows:
<interest-amount ng-repeat="interest in interests"></interest-amount>
My first question is why is this not working?
I am also confused as to how to include the currency filter in the linkFunction. What is the syntax for encoding this in Javascript rather than Angular-powered HTML?
Thanks
app.directive('interestAmount',function($filter){ // camel case, as #isha aggarwal noted
$filter('filterName')('argument');
});
Answer to your first question, the directive should be declared in camel case. So, declare the directive like this :
app.directive('interestAmount',function(){
And call it the way you are doing currently.
<interest-amount ng-repeat="interest in interests"></interest-amount>
This should take you inside the directive code.
For your second question, you should use a directive controller. Just create a controller for this directive, inject $filter in that controller and call function of that controller from link function of your directive.
Refer this : AngularJs - Use custom filter inside directive controller
I have a web page with some HTML elements which I cannot edit. I'd like to dynamically attach ng-model attributes to these and have AngularJS re-bind them to the scope. A simplified example of what I want to accomplish can be found here
<script src="//code.jquery.com/jquery-2.1.0.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script>
<script>
function MyCtrl($scope) {
$scope.myModel1 = "Hi";
$scope.myModel2 = "there";
var myModel2 = angular.element("#myModel2");
//This won't work
myModel2.attr("ng-model", "myModel2");
}
</script>
<div ng-app ng-controller="MyCtrl">
<input type="text" ng-model="myModel1"/>
<!-- I can't touch this -->
<input type="text" id="myModel2" />
</div>
You need to use $compile (docs)
$compile(myModel2.attr("ng-model", "myModel2"))($scope);
demo
When you load your page, angular uses $compile on the HTML automatically, that's how it knows which elements to assign which directives to. If you just change the attribute like you tried, angular doesn't know. You have to use $compile.