Can not get the scope variable properly - angularjs

I have a simple text box and a button and whenever user click on button the alert shows the text of textbox but I want to do it this way(I know there are a lot better ways but first I want to understand why this way does not work):
var app = angular.module('app', []);
app.factory('Service', function() {
var service = {
add: add
};
return service;
function add($scope) {
alert($scope.user.username);
}
});
app.controller('table', function(Service,$scope) {
//get the return data from getData funtion in factory
this.add = Service.add($scope);
});
As you can see I send the scope to factory and I define the user.username as follow:
<button class="btn btn-primary" ng-click="t.add(user.userName)">
But when I run this nothing happens can anyone tell me what is wrong with this code?
<body ng-app="app">
<form>
<div class="row commonRow" ng-controller="table as t">
<div class="col-xs-1 text-right">item:</div>
<div class="col-lg-6 text-right">
<input id="txt" type="text" style="width: 100%;"
ng-model="user.userName">
</div>
<div class="col-xs-2">
<button class="btn btn-primary" ng-click="t.add(user.userName)">
click me</button>
</div>
</div>
</form>
also the plnk link is as follow:
plnkr

The problem is in this line
this.add = Service.add($scope);
Here you are assigning the returned (which is undefined) value of the Service.add($scope) invocation to the this.add.
The right approach will be either
this.add = function(data) { Service.add($scope); }
or
this.add = Service.add;
// in the service factory.
function add(usrNm) {
alert(usrNm);
}

The first thing is you can't use $scope in a service.and in controller your not assaining this(object) to $scope.so $scope doesn't contain any value.
I suppose you to write like this
$scope.user = this;

Related

Angular.js $cookies : not properly saved/loaded

I am trying to use a simple input that can be retrieved by a cookie automatically.
My angular controller is :
<script>
var app = angular.module('mantis', ['ngCookies']);
app.controller('main', function($scope, $cookies) {
$scope.nom = '';
$scope.WriteNom = function () {
$cookies.put('Nom', $scope.nom);
};
$scope.ReadNom = function () {
$scope.nom = $cookies.get('Nom');
return $scope.nom;
};
});
</script>
In my page, I made a div where I can change the variable "nom" flawlessly.
The value should be loaded with ng-init (from cookie)
It changes with ng-model
And it should be saved with ng-click
<div class="container" ng-app="mantis" ng-controller="main">
<!-- Assigné à -->
<div class="col-lg-12">
<div class="input-group" ng-init="nom=ReadNom()">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input id="nom" type="text" class="form-control" name="nom" placeholder="Assigné à (id)" ng-model="nom">
<span class="input-group-btn">
<button class="btn btn-secondary" type="button" ng-click="WriteNom()">Sauvegarder</button>
</span>
</div>
</div>
(...)
And then, somewhere else, i can use "nom" where I need it by using {{nom}}
It's almost working :
The value is properly changed when I type in the input box and I can use it
The cookie is not changed when I click on the button nor it's loaded when I load the page
Remove the return part,
HTML:
<div class="input-group" ng-init="ReadNom()">
Controller:
$scope.ReadNom = function () {
$scope.nom = $cookies.get('Nom');
};
DEMO

Submit form with angular

I have the following Angular code
controller:
app.controller('MainCtrl', function($scope) {
var vm = this;
vm.job = null;
vm.create = function (job) {
vm.job = job;
}
});
HTML:
<div ng-controller="MainCtrl as vm">
<span data-ng-bind="vm.job.position"></span>
<form name="form" data-ng-submit="vm.create(vm.job)">
<label for="position">Position</label>
<input id="position" name="vm.job.position" type="text" data-ng-model="vm.job.position" />
<button>Create</button>
</form>
</div>
But when I submit the form I don't see the Position value.
Any idea why?
Because
You forgot to add ng-app to the body or html element
You're using angular 1.0.8, which is completely obsolete, and doesn't support controller as.
Note that you don't even need to submit, since the job you're binding is already vm.job. Your create(vm.job) method call does nothing: it assigns vm.job to vm.job.

select option isn't adding object in ionic

I'm trying to add a mongoose object to another mongoose object using a select bar in a form. All the other key,value pairs insert correctly, even the checkbox bool, but the select-option combo won't save the I've done this before with no problem, but in ionic, it doesn't seem to want to work. Is there a work around or am I just messing something up in the code?
$scope.addProperty = function(prop){
console.log(prop);
Props.add(prop)
.then(function(res) {
console.log(res.data);
//window.location.reload();
})
.catch(function(error){
console.log(error);
});
};
<form method = "post" class="form-inline" role="form" action = "localhost:3000/managers/newApt">
<div class="form-group">
<label class="sr-only" >Tenants:</label>
<select ng-model="prop.tenants" class="column medium-3" ng-options="manager.name for manager in allManagers"> </select>
</div>
<div class="form-group">
<label class="sr-only">Address</label>
<input type="text" class="form-control" ng-model='prop.address'>
</div>
<button type="submit" class="btn btn-default" ng-click='addProperty(prop)'>Add Property</button>
</form>
try to use this video tutorial they use var controllerName = this, inside controller and reference methods and properties of the controller through var controllerName, for example this is a controller:
angular
.module('your-app-module')
.controller('ExampleController', function ($scope, $state) {
//This var is to bind methods and vars in view(html) to this specific controller
var ExmpleCtrl = this; //this is the var that is going to replace $scope
//NOTICE no $scope but rather ExmpleCtrl
ExmpleCtrl.goToState = function (state) {
$state.go(state);
};
});
Now in your html try:
<ion-view ng-controller="ExampleController as exmpleCtrl">
<ion-content>
<!-- notice how I use exmpleCtrl instead of $scope to access controller or to pass info -->
<div ng-click="exmpleCtrl.doSomething()">
</ion-view>
If you still have doubt check this short video (ignore it's for webstorm the way they bind the controller to the a variable inside controller referenced to this is what is useful): http://blog.jetbrains.com/webstorm/2014/03/angularjs-workflow-in-webstorm/

Select some data and then persist to next controller/view in Angularjs

I am bringing in some simple data via a service that uses angular-resource like so:
angular.module('InvoiceService',
['ngResource'])
.factory('InvoiceService', function ($resource) {
return $resource('data.json');
})
.controller("DashboardListCtrl", function (InvoiceService) {
var vm = this;
InvoiceService.query(function (data) {
vm.invoices = data;
});
vm.submit = function (form) {
console.log(form)
};
});
And the html:
<form name="invoices" role="form" novalidate>
<ul>
<li ng-repeat="invoice in vm.invoices">
<input type="checkbox" id="{{'id-' + $index}}" />
<p><strong>Order:</strong></p>
<p>{{invoice.order}}</p>
</li>
<input type="submit" value="Continue" ng-click="vm.submit(invoices)" />
</ul>
</form>
Everything works fine; the data is displays in the view as expected.
The question:
What I'd like to do is be able to select a checkbox, grab the bit of data associated with that checkbox, and pass it along to the next controller/view on submit. How can I do this?
So, what do I do next? Am I on the right track?
**EDIT: added all angular code to help clarify
Posting answer as reply too big to be useful.
You should be using $scope to isolate the controller's data from the rest of the page.
Read up about ng-model http://docs.angularjs.org/api/ng/directive/ngModel and how to use it to two-way-bind checkbox value to a controller variable. No need to use theFormName if you call $scope.submit = function() { } as your ng-model variable will be available in $scope already.
angular.module('InvoiceService',
['ngResource'])
.factory('InvoiceService', function ($resource) {
return $resource('data.json');
})
.controller("DashboardListCtrl", function ($scope, InvoiceService) {
InvoiceService.query(function (data) {
$scope.invoices = data;
});
$scope.submit = function () {
// FIXME to access a property of each $scope.invoices
console.log('checkbox1=' + $scope.invoices[0].checkbox1);
};
});
Then the HTML:
<form role="form" novalidate ng-controller="DashboardListCtrl"><!-- EDIT: added ng-controller=, remove name= -->
<ul>
<li ng-repeat="invoice in invoices"><!-- EDIT: remove 'vm.' -->
<input type="checkbox" id="{{'id-' + $index}}" ng-model="invoice.checkbox1" /><!-- EDIT: added ng-model= -->
<p><strong>Order:</strong></p>
<p>{{invoice.order}}</p>
</li>
<input type="submit" value="Continue" ng-click="submit()" /><!-- EDIT: remove 'vm.' -->
</ul>
</form>

Access ng-model value

<div ng-controller="NotesController as noteCtrl">
<div class="form-group">
<input class="form-control" id="inputdefault" type="text" style="float: left;width: 90%;" ng-model="newNoteText" >
<button class="btn btn-primary" ng-click='noteCtrl.addNewNote()' type="button" style="margin-left: 0.5%"><span class="glyphicon glyphicon-plus"></span> ADD</button>
</div>
============================================
var app=angular.module('myApp',[]);
app.controller("NotesController",function(){
this.allNotes=notes;
this.note={};
this.addNewNote=function(){
alert(newNoteText);
};
});
Please let me know how to access the input text box value in my controller?
You aren't even injecting the $scope variable. You want something like this:
app.controller('NotesController', function($scope) {
$scope.allNotes=notes;
$scope.note={};
$scope.addNewNote = function(){
alert($scope.newNoteText);
};
});
No need to use this in Angular.
You need to inject the scope variable:
var app = angular.module('myApp', []);
app.controller("NotesController", function ($scope) {
$scope.allNotes = $scope.notes;
$scope.note = {};
$scope.addNewNote = function () {
console.log($scope.newNoteText);
};
});
See my fiddle.
No need to inject $scope since you're using controllerAs. Just replace this:
ng-model="newNoteText"
with this:
ng-model="noteCtrl.newNoteText"
and in your controller replace this:
alert(newNoteText);
with this:
alert(this.newNoteText);

Resources