AngularJS doesn't bind ng-model to scope - angularjs

I have the following code for my search function
<ion-content class="has-header" id="content" push-search>
<div id="search-bar">
<div class="item item-input-inset">
<label class="item-input-wrapper" id="search-input">
<i class="icon ion-search placeholder-icon"></i>
<input type="text" placeholder="Search" ng-model="query" ng-change="search()">
</label>
</div>
</div>
<div>
<// code for displaying search results//>
</ion-content>
Search Controller
.controller('SearchCtrl', function($scope, SearchFactory) {
var doSearch = ionic.debounce(function(query) {
console.log($scope);
$scope.results = SearchFactory.get({'query':$scope.query});
}, 500);
$scope.search = function() {
doSearch($scope.query);
}
})
Search Factory:
.factory('SearchFactory', function($resource) {
return $resource(url.concat('/paths/search/:query'),
{query: '#query' } ,
{ get: { method: 'GET' , isArray: true} }
);
})
When I do call Search, there is no $scope.query in my $scope:
(see) http://i.stack.imgur.com/MuxRt.png

It was solved. See this Link for more info http://jimhoskins.com/2012/12/14/nested-scopes-in-angularjs.html

Short answer is that the "query" needs to be a field in a scope search object so that it is passed by reference rather than by value, eg:
.controller('SearchCtrl', function($scope, SearchFactory) {
$scope.searchParams = {};
$scope.searchParams.query = '';
var doSearch = ionic.debounce(function(query) {
console.log($scope);
$scope.results =SearchFactory.get({'query':$scope.searchParams.query});
}, 500);

Related

ng-repeat not updating when ng-click function clicked

I have a GET function to list names, and another function that is triggered by an ng-click, that needs to update the ng-repeat where the lists of names are being at displayed by the get function. But it is not working. This is my code:
Container where the GET function displays:
<div class="container names-container" ng-controller='namesCtrl'>
<div ng-repeat='name in names.pData'>
<div class="name-box chiuv">
<p class="name-name">{{ name.name }} {{ name.last_name }}</p>
<p class="name-date">{{ name.date}}</p>
</div>
</div>
Search modal with the ng-click
<div class="output">
<input type="text" class="form-control" name="output" id="nameH" ng-model="inputName" placeholder="Search by name">
</div>
<div class="hebk"></div>
<button class="search-btn" ng-click="searchName()">SEARCH</button>
Functions
var fetch = angular.module('myapp', []);
fetch.controller('namesCtrl', ['$scope', '$http', function($scope, $http) {
$scope.getNames = function() {
$http({
method: 'get',
url: '<?= base_url(); ?>/display/getNames'
}).then(function successCallback(response) {
// Assign response to users object
$scope.names = response.data;
});
}
$scope.getNames();
$scope.searchName = function() {
$scope.names = '';
$http({
method: 'post',
data: {
name: $scope.inputName
},
url: '<?= base_url(); ?>/display/searchNames'
}).then(function successCallback(response) {
// Assign response to users object
$scope.names = [];
$scope.names = response.data;
});
}
}]);

function not execute in controller and factory

i'm developing an app that should call a controller where there are some functions, because i receive from a server (localhost in this moment) a JSON array with a structure like this:
[{
"day": "17/11/2016",
"time": "09:45"
}, {
"day": "17/11/2016",
"time": "16:50"
}, {
"day": "18/11/2016",
"time": "11:25"
}, {
"day": "18/11/2016",
"time": "12:30"
}, {
"day": "21/11/2016",
"time": "16:10"
}, {
"day": "21/11/2016",
"time": "17:25"
}]
And then i print it in two selects in a form in this way:
SELECT 1:
17/11/2016, 18/11/2016, 21/11/2016
SELECT 2:
09:45, 16:50 OR 11:25, 12:30 OR 16:10, 17:25 based on the choice in the first select
Up to this point there are no problems but now it should execute a function that post the coice of the user to the server but the app doesn't execute it.
This is my code,
SCRIPT.JS
angular
.module('demo', [])
.controller('DefaultController', DefaultController)
.factory('dataService', dataService);
DefaultController.$inject = ['dataService'];
function DefaultController(dataService) {
var vm = this;
getEvents();
function getEvents() {
return dataService.getEvents()
.then(function (data) {
vm.data = data;
return vm.data;
});
}
}
dataService.$inject = ['$http'];
function dataService($http) {
var service = {
getEvents: getEvents
};
return service;
function getEvents() {
var config = {
transformResponse: function (data, headers) {
var result = {
events: [],
schedules: []
};
var events = JSON.parse(data);
var dates = [];
for (var i = 0; i < events.length; i++) {
if (dates.indexOf(events[i].day) === -1) {
var date = events[i].day;
dates.push(date);
result.events.push({
date: date
});
}
result.schedules.push({
date: events[i].day,
time: events[i].time
});
}
return result;
}
};
return $http.get('http://<path>/api/apiTimes.php', config)
.then(getEventsCompleted)
.catch(getEventsFailed);
function getEventsCompleted(response) {
return response.data;
}
function getEventsFailed(error) {
console.error(error);
}
}
}
console.log("fine");
function submit ($http){
console.log("funzione");
var data = {};
console.clear();
var link = 'http://<path>/api/apiFix.php';
var mail = window.localStorage.getItem("mail");
$http.post(link, {giorno: data.giorno, ora: data.ora, mail: mail})
.then(function (res){
console.log("Dentro http.post");
var response = res.data;
console.log(response);
});
}
FORM HTML:
<body ng-app="demo" ng-controller="DefaultController as ctrl">
<form ng-submit="submit()">
<div class="list">
<label class="item item-input item-select">
<div class="input-label">
Giorno:
</div>
<select ng-options="event as event.date for event in ctrl.data.events" ng-model="data.giorno">
<option disabled>Seleziona un giorno </option>
</select>
</label>
</div>
<div class="list">
<label class="item item-input item-select">
<div class="input-label">
Ora:
</div>
<select ng-options="schedule as schedule.time for schedule in ctrl.data.schedules | filter: { date: data.giorno.date}" ng-model="data.ora" ng-disabled="!data.giorno">
<option disabled>Seleziona un orario </option>
</select>
</label>
</div>
</div>
</div><br>
<ul class="list">
<li class="item item-toggle">
&Egrave un'urgenza?
<label class="toggle toggle-assertive">
<input type="checkbox">
<div class="track">
<div class="handle"></div>
</div>
</label>
</li>
</ul>
<div align="center">
<input class="button button-calm" type="submit" name="submit" value="Prenota !">
</div>
</form>
</body>
I have no errors in console but the function "submit" it isn't execute.
How can i solve this problem?
Thank's
You have a couple of errors. You need to fix at least these
On your controller (you will need to inject $http)
DefaultController.$inject = ['dataService', '$http'];
function DefaultController(dataService, $http) {
var vm = this;
vm.submit = function (){
console.log("funzione");
var data = vm.form; // IMPORTANT
console.clear();
var link = 'http://<path>/api/apiFix.php';
var mail = window.localStorage.getItem("mail");
$http.post(link, {giorno: data.giorno, ora: data.ora, mail: mail})
.then(function (res){
console.log("Dentro http.post");
var response = res.data;
console.log(response);
});
};
}
And in your form as I mention in the comment, since you are using the controller as approach you need to include ctrl
<form ng-submit="ctrl.submit()">
And rename your ng-model variables to
ng-model="ctrl.form.ora" //ng-model="data.ora"
ng-model="ctrl.form.giorno" //ng-model="data.giorno"

ng-model data not getting when saving the data

here save the ng-model is newattendance saving to database. "newattendance._id" is not taken as a ng-model.how to make it "newattendance._id" is ng-model
<select class="form-control" ng-options="item.empcode as item.empcode for item in totemplist" ng-model="item.empcode">
</select>
<input type="text" ng-repeat="newattendance in totemplist" ng-model="newattendance._id" ng-show="item.empcode ==newattendance.empcode" style="width:200px;" ><br>
<input placeholder="Enter Attendacne Date" ng-model="newattendance.doa">
<button class="btn btn-primary" ng-click="checkOut()">checkOut</button>
Controller
EmpMasterController.controller("AttendanceController", ['$scope', 'AttendanceFactory',"EmpAddService", function($scope, AttendanceFactory,EmpAddService){
$scope.newattendance={};
$scope.totemplist=EmpAddService.getAllEmpAddItems();
console.log($scope.totemplist);
$scope.checkIn = function(){
AttendanceFactory.addAttendance($scope.newattendance);
$scope.newattendance = {}
}
$scope.getAllAttendance = function(){
console.log("$$$$$"+$scope.newattendance._id)
$scope.attendancedetails =AttendanceFactory.getAllAttendance($scope.newattendance._id);
}
}])
Factory
EmpFactModule.factory("AttendanceFactory", function($resource, RES_URL){
var attendanceResource = $resource(RES_URL+"attandence/:id/:attid",
{"id": "#id", "attid": "#attid"}, {update: {method: "PUT"}})
var attendanceDetails;
return {
addAttendance: function(newattendance){
console.log("..1.. " + newattendance._id)
attendanceResource.save({"id":newattendance._id}, newattendance, function(data){
console.log("Add Success ")
}, function(data, status){
console.log("Add Failed*****");
})
},
getAllAttendance: function(_id){
console.log("..#.. " + _id)
attendanceDetails = attendanceResource.query({"id": _id});
return attendanceDetails;
},
}
})
please help me how make it as ng-model and how to save this...
I've create a JSFiddle for you which hopefully will help you understand the 2 way binding in angular.
you dont need to pass the newattendance object to the check-out function, it is already saved on the scope.
HTML:
<div ng-app="app">
<div ng-controller="formValidation">
<div>
<div>
<span>User Name</span>
<input type="text" placeholder="John" ng-model="newattendance._id">
<span>
<button ng-click="submit()">
check out
</button>
</span>
</div>
</div>
<pre>{{newattendance._id}}</pre>
</div>
</div>
JS:
var app = angular.module('app', []);
app.controller('formValidation', function($scope) {
$scope.submit=function(){
var formPost = {
"Username":$scope.newattendance._id
};
console.log(formPost);
}
});

Angular updating and clearing factory variables

I'm creating a single page app in which a user searches for a term, the result gets saved in a variable, and a new page is routed that displays the result. I have this functionality working, however I want the variable to be cleared when the user returns to the previous page and most importantly when the user logs out. What's the proper way to do this? I want the factory to save things for certain pages that I want, and clear them for certain pages I don't want like "home" or "logout".
Factory:
angular.module('firstApp')
.factory('fact', function () {
var service = {};
var _information = 'Default Info';
service.setInformation = function(info){
_information = info;
}
service.getInformation = function(){
return _information;
}
return service;
});
Controller:
angular.module('firstApp')
.controller('InformationCtrl', function($scope, $http, $location, fact) {
$scope.message = 'Hello';
$scope.result = fact.getInformation();
$scope.sub = function(form) {
console.log($scope.name);
$scope.submitted = true;
$http.get('/wiki', {
params: {
name: $scope.name,
}
}).success(function(result) {
console.log("success!");
$scope.result = result;
fact.setInformation(result);
$location.path('/informationdisplay');
});;
}
});
Routes
angular.module('firstApp')
.config(function ($routeProvider) {
$routeProvider
.when('/information', {
templateUrl: 'app/information/input.html',
controller: 'InformationCtrl',
authenticate : true
})
.when('/informationdisplay', {
templateUrl: 'app/information/results.html',
controller: 'InformationCtrl',
authenticate : true
});
});
input.html
<div class="row">
<div class="col-md-6 col-md-offset-3 text-center">
<p>{{result}}</p>
<form class="form" name="form" ng-submit="sub(form)" novalidate>
<input type="text" name="name" placeholder="Name" class="form-control" ng-model="name">
</br>
<button class="btn btn-success" type="submit" class="btn btn-info">Check</button>
</div>
</div>
results.html
<div ng-include="'components/navbar/navbar.html'"></div>
<div class="row">
<div class="col-sm-4 col-sm-offset-4">
<h2>Information Results</h2>
<p>{{result}}</p>
</div>
</div>
</div>
If you want it to wipe the value when they change routes (which logout should change routes also, I assume), you can watch the $routeChangeStart event and have it wipe the value whenever it occurs. You put that function in the module.run block:
app.run(function ($rootScope, fact) {
$rootScope.$on("$routeChangeStart",function(event, next, current){
fact.setInformation(null);
});
});

Why won't my view template bind to a scope variable with AngularJS?

My view is:
<div class="container" ng-controller="MyController">
<div class="row">
<div class="col-md-8">
<textarea class="form-control" rows="10" ng-model="myWords" ng-change="parseLanguage()"></textarea>
</div>
<div class="col-md-4" ng-show="sourceLanguage !== null">
Language: {{ sourceLanguage }}
</div>
</div>
</div>
My controller is:
webApp.controller('MyController', [
'$scope', '$rootScope', 'TranslateService', function($scope, $rootScope, CodeService) {
$scope.init = function() {
return $scope.sourceLanguage = null;
};
$scope.parseLanguage = function() {
return TranslateService.detectLanguage($scope.myWords).then(function(response) {
console.log($scope.sourceLanguage);
$scope.sourceLanguage = response.data.sourceLanguage;
return console.log($scope.sourceLanguage);
});
};
return $scope.init();
}
]);
The console logs show the right data. But in the view, sourceLanguage never updates. Why would this be?
In case the promise you are evaluating is not part of the Angular context you need to use $scope.$apply:
$scope.parseLanguage = function() {
TranslateService.detectLanguage($scope.myWords).then(function(response) {
$scope.$apply(function() {
$scope.sourceLanguage = response.data.sourceLanguage;
});
});
};

Resources