I just began to study angular, tried to make some kind of SPA, but faced with problem of editing data in it. The obect is visible in console, but it hasn't appear on page, what I did wrong?
Here my controller:
var app = angular.module("testModule", ['ngRoute']);
app.config(function ($routeProvider){
$routeProvider.when('/', {
templateUrl: 'pages/main.html',
controller: 'addCtrl'
})
.when('/save', {
templateUrl: 'pages/save.html',
controller: 'editCtrl'
})
.when('/edit', {
templateUrl: 'pages/edit.html',
controller: 'addCtrl'
})
})
app.service('dataService', function($http) {
var data = {};
data.list = [];
var getData = function() {
$http.get("model/data.json").then(function (response) {
data.list = response.data;
});
}
return {
getDataFromJson: getData,
getData: data,
}
});
app.controller("mainCtrl", function($scope, dataService) {
dataService.getDataFromJson();
});
app.controller("editCtrl", function($scope, dataService) {
$scope.data = dataService.getData;
$scope.editData = function(adverse){
$scope.adverse= adverse;
console.log($scope.adverse)
}
});
and the part of page:
<div class="panel">
<form name="addForm" >
<div class="well" >
<div class="form-group">
<label for="name">Name:</label>
<input type='text' id="name" class="form-control" ng-model="adverse.name" placeholder={{adverse.name}} />
<label for="shop">Shop:</label>
<input type='text' id="shop" class="form-control" ng-model="adverse.shop" placeholder="{{adverse.shop}}" />
<label for="begin">Begin:</label>
<input id="begin" class="form-control" ng-model="adverse.begin" placeholder="{{adverse.begin}}" >
<label for="end">End:</label>
<input id="end" class="form-control" ng-model="adverse.end" placeholder="{{adverse.end}}" />
<button type="submit" class="btn btn-primary btn-block add_btn" ng-click="editData(adverse)">
Edit
</button>
</div>
</div>
</form>
</div>
Also here is a screenshot: the props of object suppose to be in the inputs but it hasn't.
enter image description here
If possible can you give me an example how I can do it by another way?
Recreated your scenario in this plunker. But it works. Please have a look at this plunker where you alo can see the StateProvider which is used instead of NgRoute
One thing I see which is incorrect is that you are sending the adverse object in the function and then setting the param to the scope adverse.
The thing is that the $scope.adverse already holds the values so you don't need to pass the value and setting it to the scope again. Remeber the scope is your glue between the view and ctrl
$scope.editData = function(){
console.log($scope.adverse)
}
Related
I am facing this problem while selecting file and showing its name on span.
So basically I am trying that whenever I select some file I want to change the span Tag. This is my view
<form name="fileUploadForm" ng-submit="submitFile(fileUploadForm.$valid)">
<div class="form-group upload-btn-wrapper">
<input type="file" class="form-control" id ="myFileField" file-input="patient_file" required />
<button class="csv-upload-btn">choose file</button>
<span id="file-chosen">{{ patient_file }}</span>
</div>
<div class="form-group">
<input type="submit" value="Upload" class="btn btn-primary">
</div>
</form>
following is my directive code
(function() {
angular.module('practimyze.dashboard')
.directive('csvUploader', ["$parse", function($parse) {
return {
restrict: 'EA',
templateUrl: "dashboard/breakdown/csv-uploader/csv-uploader.tpl.html",
replace: true,
controller: function($scope, valueHandler, Auth, $rootScope, blockUi, DashboardApi, fileUploadService, apiLinks, toaster){
},
link: function(scope, element, attrs) {
var model = $parse(attrs.csvUploader);
var modelSetter = model.assign;
element.bind('change', function() {
scope.$apply(function() {
modelSetter(scope, element[0].patient_file);
});
});
}
};
}]);
})();
Initially I did this
$parse.assign(scop, element[0].files);
this was getting me error that parse has not function assign. Then I changed it to what i have written now it says (modelSetter is not a function).
I am not sure where i am doing wrong, Please help me out thanks
Edited:
this is the fiddle link, it seems to be working perfect there fiddle link
I am creating a web app, where I have one page which is home.html and about.html. In the home.html I have list of users, and when they click on one of the users, it goes to about.html, but does not show the users info. Can anyone check my code, to see what I have done wrong. Thanks in advance.
Here is my code. (home.html)
<form name="myForm">
<label>Search
<input type="text" size="35" ng-model="userSearch">
</label>
</form>
<br/>
<label>Filters</label>
<button type="button" class="btn btn-link">+ Add Filter</button>
<hr>
<legend>Users</legend>
<div class="people" ng-repeat="person in userInfo.lawyers | filter:userSearch" >
<a href="#/lawyer/{{ person.id }}">
<img ng-src="{{person.imgUrl}}"/>
<span class="name">{{person.firstName}} </span>
<span class="name">{{person.lastName}} </span>
<p class="title">{{person.title}} </p>
<span class="date">{{person.date}} </span>
</a>
</div>
About.html
<div class="people-view">
<h2 class="name">{{person.first}}</h2>
<h2 class="name">{{person.last}}</h2>
<span class="title">{{person.title}}</span>
<span class="date">{{person.date}} </span>
</div>
<div class="list-view">
<form>
<fieldset ng-disabled="inactive">
<legend>Basic Info</legend>
<b>First Name:</b>
<input type="text" ng-model="person.first">
<br>
<b>Last Name:</b>
<input type="text" ng-model="person.last">
<br>
<b>Email:</b>
<input type="email" ng-model="person.email">
<br>
<b>Phone:</b>
<input type="num" ng-model="person.phone">
<br>
<b>Website:</b>
<input type="text" ng-model="person.website">
<br>
<b>Education:</b>
<input type="text" ng-model="person.education">
<br>
<b>Education Year:</b>
<input type="text" ng-model="person.year">
<br>
</form>
</div>
</div>
App.js
var app = angular.module("Portal", ['ngRoute', 'ui.bootstrap' ]);
app.controller('MyCtrl', function($scope) {
//form setting to true
$scope.inactive = true;
$scope.confirmedAction = function() {
isConfirmed.splice($scope.person.id, 1);
location.href = '#/lawyer';
}
});
app.config(function ($routeProvider) {
$routeProvider
.when("/lawyer", {
controller: "HomeController",
templateUrl: "partials/home.html"
})
.when("/lawyer/:id", {
controller: "LawyerController",
templateUrl: "partials/about.html"
})
.otherwise({
redirectTo: '/lawyer'
});
});
Controller
app.controller('LawyerController', ['$scope', 'people', '$routeParams',
function ($scope, people, $routeParams) {
people.getUserInfo().then(function (response) {
$scope.person = people.getUserInfo();
console.log($scope.person.lawyers);
}, function (error) {
console.log(error)
});
}]);
HomeController
var isConfirmed = false;
app.controller('HomeController', function($scope, people, $http) {
if (!isConfirmed) {
people.getUserInfo().then(function (response) {
$scope.userInfo = response.data;
isConfirmed = $scope.userInfo;
console.log($scope.userInfo.lawyers);
}, function (error) {
console.log(error)
});
}
});
Services
app.factory('people', ['$http', function($http) {
var userInfo = {
getUserInfo: function () {
return $http.get('https://******************');
}
};
return userInfo;
}]);
As others mentioned, your whole code is in wrong way! but I will try to help as much as I can.
You don't have any method in LawyerController to get the data, so let's begin from that :
change your $routeProvider in app.js like this to have a method :
$routeProvider
.when("/lawyer", {
controller: "HomeController",
templateUrl: "partials/home.html"
})
.when("/lawyer/:id", {
controller: "LawyerController",
templateUrl: "partials/about.html",
method: 'lawyerInit'
})
.otherwise({
redirectTo: '/lawyer'
});
Then change your LawyerController to something like this :
app.controller('LawyerController', ['$scope', 'people', '$routeParams',
function ($scope, people, $routeParams) {
$scope.lawyerInit = function(){
people.getUserInfo().then(function (response) {
$scope.getAll= people.getUserInfo();
for (var i=0; i<=$scope.getAll.length -1; i++){
if($scope.getAll[i].lawyers.id==$routeParams.id){
$scope.person= $scope.getAll[i];
}
}
console.log($scope.person.lawyers);
}, function (error) {
console.log(error)
});
}
}]);
Hope this work, I was not sure how is your json response, if you get error in this line if($scope.getAll[i].lawyers.id==$routeParams.id) you need make sure the id where is exactlly in your json object.
I recently updated my Angular from 1.5.x to 1.6.4 and now, when I go to a form, I get the below error message whenever I try to type something up in the form/textbox:
TypeError: Attempted to assign to readonly property.
This is my controller:
mainApp.controller('newPostController', ['$scope', '$http', function($scope, $http){
$scope.post = '';
$scope.postCreated = false;
$scope.makeNewPost = function() {
$http.post('/api/post', {
title: $scope.post.title,
})
.then(function(res){
$scope.postCreated = true;
//extra code not related to the form itself...
};
}]);
My HTML looks like this:
<form ng-submit="makeNewPost()">
<div class="form-group">
<label for="title" class="control-label">Title</label>
<input type="text" autocomplete="off" class="form-control" ng-model="post.title" id="title" required="required">
</div>
<input type="submit" value="Submit">
</form>
I looked this error up and everything I am seeing has nothing to do with what my set up is like.
Please help me out on this. I don't know where to go from here.
Thanks
Try this...
you have initialized $scope.post = ''; as a string. But that should be $scope.post = {}; an object.
var mainApp = angular.module('app', []);
mainApp.controller('newPostController', ['$scope', '$http', function($scope, $http) {
$scope.post = {};
$scope.postCreated = false;
$scope.makeNewPost = function() {
console.log($scope.post.title);
$http.post('/api/post', {
title: $scope.post.title,
})
.then(function(res) {
$scope.postCreated = true;
//extra code not related to the form itself...
});
}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app='app' ng-controller='newPostController'>
<form ng-submit="makeNewPost()">
<div class="form-group">
<label for="title" class="control-label">Title</label>
<input type="text" autocomplete="off" class="form-control" ng-model="post.title" id="title" required="required">
</div>
<input type="submit" value="Submit">
</form>
</div>
So I am using ionic to build a hybrid app. Just to be clear, this works flawlessly with android!
Here is my login html:
<body ng-app="starter">
<head>
<script src="phonegap.js"></script>
</head>
<ion-header-bar align-title="center" class="bar-positive" ng-controller="BackBtnCtrl">
<button class="button" ng-click="goBack()"><<</button>
<h1 class="title">Push Notifications</h1>
</ion-header-bar>
<ion-content>
<div class="list">
<form style="display: block; margin: 100px">
<label class="item item-input">
<input type="text" ng-model="name" placeholder="Name">
</label>
<label class="item item-input">
<input type="password" ng-model="password" placeholder="Password" style="text-align: center">
</label>
<label class="item item-input">
<input type="email" ng-model="email" placeholder="Email" style="text-align: center">
</label>
<label class="item item-input">
<input type="text" ng-model="company" placeholder="Company Name" style="text-align: center">
</label>
<button class="button button-block button-positive" type="submit" ng-click="doLogin()">Register</button>
</form>
</div>
</ion-content>
</body>
Now in my app.js I declare the controller for the ion-content as:
.state('login', {
url: '/login',
templateUrl: 'templates/login.html',
controller: 'LoginCtrl'
})
and when I access, for example, $scope.email in the android app, it returns correctly. But when I access $scope.email in the iOS app, I get undefined. Has anyone ever heard of this issue?
controller:
.controller('LoginCtrl', function($scope, $rootScope, $http, $state, $ionicPlatform) {
if(window.localStorage.getItem("loggedIn") == undefined || window.localStorage.getItem("loggedIn") == null) {
// This function only gets called when the register button gets hit. It posts to the server to store the users registration data
$scope.doLogin = function() {
if ($scope.name == undefined || $scope.password == undefined|| $scope.email == undefined|| $scope.company == undefined) {
window.plugins.toast.showWithOptions(
{
message: 'Please Fill in ALL Fields',
duration: 'long',
position: 'middle'
});
alert($scope.email);
alert("returning");
return;
}
alert($scope.email);
According to the official Angular documentation, you should declare the controller like this:
myApp.controller('GreetingController', ['$scope', function($scope) {
$scope.greeting = 'Hola!';
}]);
So, try change your code in the following way:
.controller('LoginCtrl', ['$scope', '$rootScope', '$http', '$state', '$ionicPlatform', function($scope, $rootScope, $http, $state, $ionicPlatform) {
if(window.localStorage.getItem("loggedIn") == undefined || window.localStorage.getItem("loggedIn") == null) {
// This function only gets called when the register button gets hit. It posts to the server to store the users registration data
$scope.doLogin = function() {
if ($scope.name == undefined || $scope.password == undefined|| $scope.email == undefined|| $scope.company == undefined) {
window.plugins.toast.showWithOptions(
{
message: 'Please Fill in ALL Fields',
duration: 'long',
position: 'middle'
});
alert($scope.email);
alert("returning");
return;
}
alert($scope.email);
This might sound absolutely crazy..
First let me thank all the responses. I have learned a lot with how things should be and how I need to fix my code to be 'standard'. Like using . object instead of primitive strings. Thank You.
But I have solved my issue.The thing that was making my fields undefined, was that I had type='email' and if they just entered in something other than an email, it came back undefined. I don't know how, but that fixed it. I changed type='text' and it fixed my issues.
I am using the MEAN framework - I have a basic form (as per below) that when data is entered it is sent to a rest API which then has a function that uses Mongoose to save data. That is all good... however i'm stuck on something more basic!
After a user has submitted this form it lands on a blank page with the api/img/add, how do i go back to my original page? I tried adding ng-submit="fetchImages()" within the form tag and then implementing a function in a script (also shown below) but for some reason this was not working, am i missing the point and doing something really wrong?
Thanks in advance
<form action="api/img/add" method="post" enctype="multipart/form-data">
<div>
<label for="image">Select an image</label>
<input type="file" name="image" id="image">
</div>
<div>
<label for="title">Title</label>
<input type="text" name="title" id="title">
</div>
<input type="submit">
</form>
< script >
angular.module('app', []).controller('main', ['$scope', '$http',
function($scope, $http) {
$scope.images = [];
$scope.fetchImages = function() {
$scope.images = [];
$http.get('api/img').then(function(res) {
$scope.images = JSON.parse(res.data);
}, function(res) {
console.log(res.statusText);
});
}
$scope.fetchImages();
}
]); < /script>
If you literally want to go back to the last page, you could use:
$window.history.back();
In your example, I would create the function in the controller as outlined below, and change
<input type="submit">
to
<input type="submit" ng-click="goHome()">
I created an über-simple plunk here with a button that will take you back:
https://plnkr.co/edit/wzMlPF9kOmrGg01mOnBB?p=preview
JS
app.controller('ctrl',function($scope,$window){
$scope.goHome = function() {
$window.history.back();
}
});
HTML
<button ng-click="goHome()">Go Home</button>
Try this:
In html
<form ng-submit="submitData()">
<div>
<label for="image">Select an image</label>
<input type="file" ng-model="formdata.image" id="image">
</div>
<div>
<label for="title">Title</label>
<input type="text" ng-model="formdata.title" id="title">
</div>
<input type="submit">
</form>
In your controller:
angular.module('app', []).controller('main', ['$scope', '$http',
function($scope, $http) {
$scope.formdata = {};
$scope.images = [];
$scope.fetchImages = function() {
$scope.images = [];
$http.get('api/img').then(function(res) {
$scope.images = JSON.parse(res.data);
}, function(res) {
console.log(res.statusText);
});
}
$scope.fetchImages();
//this function will post data to your api without refreshing the page
$scope.submitData = function(){
$http.post('api-comes-here', $scope.formdata).then(function(res) {
//handle success
}, function(error) {
//handle error
});
}
}