Cannot get ng-model binding value - javascript

I'm using ionic to build a webapp, and I want to use ng-model bind input form value.
It is weird that I am not getting model.cellphone's value, but I got model.password's value.
Currently I cannot figure this out. Can anybody help me?
html:
<ion-view>
<ion-content class="login-content">
<div class="login-form">
<input type="text" class="login-form-cellphone" ng-model="model.cellphone" placeholder="please input your phonenumber" required minlength="11" maxlength="11"/>
<input type="password" class="login-form-password" ng-model="model.password" placeholder="please input your password" required/>
<button class="login-form-btn" ng-click="login()">Login</button>
</div>
</ion-content>
</ion-view>
js:
.controller('LoginCtrl', ['$scope', '$state', '$stateParams', 'RouteService', 'ApiService', function ($scope, $state, $stateParams, RouteService, ApiService) {
var route = 'app.home.login';
var params = $stateParams;
$scope.model = {};
$scope.doRefresh = function () {
$scope.isChecked = true;
};
$scope.goBack = function () {
$state.go(params.previewRoute);
};
$scope.clickCheck = function () {
$scope.isChecked = !$scope.isChecked;
};
$scope.login = function () {
console.log($scope.model.cellphone, $scope.model.password, $scope.isChecked);
if (!$scope.model.cellphone) {
console.log('cellphone');
return;
}
if (!$scope.model.password) {
console.log('password');
return;
}
if (!$scope.isChecked) {
console.log('isChecked');
return;
}
ApiService.login(
$scope.model.cellphone,
$scope.model.password,
null,
function (status) {
if (status === 1)
$state.go(params.previewRoute);
})
};

Related

$http.post from angular form not sending any data

I have a form that is posting /api/tradelink but it doesn't send any body or data with it.
HTML :
<form ng-submit="sendTradelink()">
<md-input-container class="md-accent">
<label>Enter your tradelink</label>
<input ng-model="tradelink">
</md-input-container>
<md-button type="submit" class="md-raised md-accent">Send</md-button>
</form>
Services :
.factory('Auth', ['$http', '$api', '$window', function ($http, $api, $window) {
var authFactory = {};
authFactory.authenticate = function(){
$http.post($api.url + 'auth')
.successs(function(url){
$window.location.href = url;
});
};
authFactory.send = function () {
return $http.post($api.url + 'tradelink');
};
return authFactory;
}]);
Controller ;
.controller('AppCtrl', ['$scope', 'Auth', '$location', '$cookies', function ($scope, Auth, $location, $cookies) {
var sidTemp = 'needtomakeitanewvalue';
$scope.checklogin = function () {
$scope.sid = $cookies.get('sid2');
console.log($scope.sid);
}
$scope.sendTradelink = function () {
Auth.send($scope.tradelink)
.success(function (res) {
$scope.sidTemp = 'needtomakeitanewvalue';
$cookies.put('sid2', sidTemp);
$location.path('/');
});
}
$scope.auth = function () {
Auth.authenticate();
}
}])
Server side holding api request, nothing inside req.body or req.params. Both show as empty objects.
api.post('/tradelink', function(req, res){
console.log(req.user.steamId);
console.log(req.params);
console.log(req.body);
res.json({
success: true,
message: 'tradelink received'
})
});
Check the Angular docs for $http.post
You are calling Auth.send($scope.tradelink), but your authFactory.send() function needs to accept this tradelink value and then be used as a data param to $http.post()
So:
authFactory.send = function (tradelink) {
return $http.post($api.url + 'tradelink', {tradelinkId: tradelink });
};

How to use ng-model / $scope with Angular Factory and Controller

// SERVICES
app.factory('searchFactory', ['$http', function($http) {
return $http.post("/api", { tag: "food" });
}]);
// CONTROLLERS
app.controller('MainController', ['$scope', 'searchFactory', function ($scope, searchFactory) {
$scope.submit = function () {
searchFactory.then(function(response) {
$scope.recipeData = JSON.parse(response.data);
});
};
// HTML
<form ng-submit="submit()">
<div class="form-group">
<input type="text" ng-model="recipeTag" class="form-control" />
<input type="submit" class="btn btn-primary" value="Find Recipes" />
</div>
</form>
Does anyone know how I can use $scope.recipeTag from ng-model to replace "food" in the factory? I need to be able to pass the form input as a parameter into the factory.
you need to create a funtion that expects a parameter in your factory.
Example:
var factory= {
post: function(customTag) {
return $http.post("/api", { tag: customTag });
}
};
return factory;

How pass variables to directive from controller?

HTML:
<div ng-repeat="item in productArr">
{{ item.title }}
</div>
<div category-page-navigation current-page='currentPage' category-products-count='productsCount'></div>
JS:
.controller('categoryController', ['$scope', '$location', '$http', '$q', '$window', '$stateParams', function($scope, $location, $http, $q, $window, $stateParams) {
$scope.currentPage = 1;
$scope.productsCount = 0;
var GET = {
getProductData: function() {
var defer = $q.defer();
$http.post('services/loadProduct.php', {
'id' :1,
}).then(function(response) {
defer.resolve(response);
}, function(response) {
defer.resolve([]);
});
return defer.promise;
}
};
var getData = {
getProduct: function() {
var productData = GET.getProductData();
$q.all([productData]).then(
function(response) {
$scope.productArr = response[0].data.products;
$scope.productsCount = response[0].data.products.length;
});
}
};
getData.getProduct();
}])
.directive('categoryPageNavigation', function($compile, $parse) {
return {
scope: {
currentPage: '=currentPage',
categoryProductsCount: '=categoryProductsCount'
},
link: function (scope, element, attrs) {
debugger;
// Here scope.categoryProductsCount = undefined
// ...
$scope.$watch(scope.currentPage, function(value) {
// ...
});
}
};
});
I try to form new HTML for navigation to manipulate with HTML I get from ng-repeat.
In directive I need currentPage(from start =1) and total count of items from ng-repeat(length of array) witch I get from service. How I can pass variables to directive? First I need to get variables from service(ajax request or something else) then pass variables(some ather data) to directive.
If I understood correctly what you mean. Here is a code pen example on how to shared data between you controller and your directive.
A good read to understand the code below:https://docs.angularjs.org/guide/providers
http://codepen.io/chocobowings/full/Xmzxmo/
var app = angular.module('app', []);
//-------------------------------------------------------//
app.factory('Shared', function() {
return {
sharedValue: {
value: '',
}
};
});
//-------------------------------------------------------//
app.controller('ctrl', function($scope, Shared) {
$scope.model = Shared.sharedValue;
});
//-------------------------------------------------------//
app.directive('directive', ['Shared',
function(Shared) {
return {
restrict: 'E',
link: function(scope) {
scope.model = Shared.sharedValue;
},
template: '<div><input type="text" ng-model="model.value"/></div>'
}
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
Ctrl:
<div ng-controller="ctrl">
<input type="text" ng-model="model.value" />
<br/>
</div>
Directive:
<directive value="model.value"></directive>
</div>

Angular.js | Sharing a ngModel

So, this is my HTML.
<input type="text" id="ghusername" ng-model="username" placeholder="Github username...">
<span id="ghsubmitbtn" ng-click="getUsers()">Pull User Data</span>
This is my Controller A.
app.controller("homeController", ["$scope", "$http", function ($scope, $http) {
$scope.getUsers = function () {
$http.get("https://api.github.com/users/" + $scope.username)
.success(function (data) {
//some stuff
})
And this is B (for posting sake). How do I get this username on the HTML ngModel, so that I can show it in another controller? ex:
app.controller("reposController", ["$scope", "$http", function ($scope, $http) {
$scope.getRepos = function () {
$http.get("https://api.github.com/users/" + $scope.username + "/repos")
.success(function (data) {
// some stuff
})
};
I've tried to user services, factories and even $rootScopes, but they just don't seem to work, any help? Btw, if I wasn't clear tell me and I will edit the post, Thank you.
EDIT: I ended up using $rootScope, I know it isn't the best idea but it was a minor thing. I'll keep all your answers for reference tho, as I'm sure they all work but I'm just too dumb to implement them.. Thank you.
You must to refernce $rootScope into your controllers:
app.controller("homeController", ["$scope", "$http","$rootScope", function ($scope, $http, $rootScope) ...
and after that just access rootscope variables:
controller1: $rootScope.someValue = "some value";
Controller2: $scope.controllerScopeValue = $rootScope.someValue;
Use service
app.service('name', [function(){}])
Then add 'name' to both the controllers like
app.controller("reposController", ["$scope", "$http", 'name', function ($scope, $http, name) {
$scope.name = name;
Then you can access it like
name.username
and in html
<input type="text" id="ghusername" ng-model="name.username" placeholder="Github username...">
Try something like this
http://jsfiddle.net/devkickstart/nevyhdn0/2/
Using a factory you can share the data between controller like so...
<div ng-app="myApp">
<div data-ng-controller="reposCtrl">
<input type="text" id="ghusername" ng-model="username" placeholder="Github username..." ng-init="getRepos()" />
{{data}}
</div>
<div data-ng-controller="homeCtrl"> <span id="ghsubmitbtn" ng-click="getUsers()">Pull User Data</span>
{{otherData}}
</div>
</div>
angular.module("myApp", [])
.factory("dataFact", ["$rootScope", function ($rootScope) {
var myData = "value from factory";
return {
getData: function () {
return myData;
},
setData: function (newVal) {
this.myData = newVal;
}
}
}]).controller("homeCtrl", ["$scope", "dataFact", function ($scope, dataFact) {
$scope.getUsers = function () {
$scope.otherData = dataFact.getData();
}
}]).controller("reposCtrl", ["$scope", "dataFact", function ($scope, dataFact) {
$scope.getRepos = function () {
$scope.username = dataFact.getData();
}
}]);
With some assumptions about your data model, this should work.
It creates a shared singleton object. One controller adds the user (or whatever data) as an attribute of that. Then other controllers, or indeed the same controller if it is reloaded, can then access the same data on shared.
Note here that a service just returns a singleton of anything, it doesn't need code or methods. In this case, it's easier to use a value instead which is shorthand for function() { return {}; } and works just as well.
Remember to inject shared wherever it is needed.
app.controller("homeController", ["$scope", "$http", "shared", function ($scope, $http, shared) {
$scope.getUsers = function () {
$http.get("https://api.github.com/users/" + $scope.username)
.success(function (data) {
shared.user = data.user; // or wherever it comes from
//some stuff
})
app.controller("reposController", ["$scope", "$http", "shared", function ($scope, $http, shared) {
$scope.getRepos = function () {
$http.get("https://api.github.com/users/" + shared.user.name + "/repos")
.success(function (data) {
// some stuff
})
};
app.value('shared', {});

Binding data to AngularUI dialog

I'm trying to write a simple angularapp to allow the teachers to edit their class information. I'm using angular-ui dialog directive to get the lightbox. On userclick I've written a function to pass the data to the modal and open the dialog. But for some reason the data is not properly binded.
This is my controller.js
'use strict';
define(['app' ], function(app) {
app.controller('TeacherClasses',
[ '$scope', '$http', '$dialog','$location', 'teacherClassService',
function($scope, $http, $dialog, $location, teacherClassService) {
$scope.newClass={};
$scope.show = {"createClassModal": false};
$http.get('/grades').success(function(data) {
$scope.grades = data;
});
$scope.newClass.grade = "Grade";
$scope.setGrade = function(grade){
$scope.newClass.grade = grade;
};
$scope.fetchStudentGroups = function(){
$http.get('/teacher/studentGroups').success(function(data) {
$scope.studentGroups = data;
});
};
$scope.fetchStudentGroups();
$scope.createClass = function(){
$http.post('/studentGroup', $scope.newClass).
success(function(data, status, headers, config) {
$scope.show.createClassModal = false;
//Clearing it out for next time
$scope.newClass = {};
$scope.fetchStudentGroups();
}).
error(function(data, status, headers, config) {
});
console.log($scope.newClass);
};
$scope.openDialog = function(studentGroup, dialog){
$scope.newClass = angular.copy(studentGroup);
$scope.opts = {
backdrop: true,
keyboard: true,
backdropClick: true,
templateUrl: '/assets/partials/teacher/manage/editClassInfo.html',
resolve: {
data: function(){
return $scope.newClass;
}
}
};
var modal = $dialog.dialog($scope.opts);
modal.open();
}
}]);
return app;
});
And this is my partial
<div class="modal-header">
Edit Class
</div>
<div class="modal-body">
<form class="form-horizontal">
<div class="control-group">
<input type="text" ng-model="newClass.name" class="span4">
</div>
<div class="control-group">
<select ui-select2 data-placeholder="Choose a grade" id="grades" class="span4">
<option></option>
<option ng-repeat="grade in grades" ng-model="grades" >{{grade}}</option>
</select>
</div>
<label>Students {{newClass.noOfStudents}}</label>
<label>{{newClass.name}}</label>
</form>
</div>
<div class="modal-footer"></div>
My module definitions are in app.js
'use strict';
define([ 'angular' ], function(angular) {
var myModule = angular.module('myApp',
[ 'ngResource', 'ui', 'infinite-scroll', 'ngDragDrop', 'blueimp.fileupload','ui.bootstrap.dialog', 'ui.bootstrap.modal',
'ui.bootstrap.dropdownToggle', 'LoadingIndicator', 'http-auth-interceptor']);
myModule.value('ui.config', {
select2 : {
allowClear : true
},
redactor: {
plugins: ['fullscreen']
}
});
return myModule;
});
But none of these values are tied back to the view. What am I doing wrong here?

Categories

Resources