AngularJS same html site for insert and update - html

This one is going to be a long one :)
So here is the idea, I wanna use same html page for two controllers , problem is , that page in insert state wont load , because of ng-repeat="employee in employee" because its non existent in insert controller.
What my repeater does it just fills textboxes , it doesnt repeat anything , its just a single form and it fills information of that one single employee , am i doing this wrong ?
employeeUpdate works like a charm , problem is in employeeInsert , is there a posibility that it can fill textboxes without ng-repeat part , because it does not work without it , but it does fill comboBox/select options without it.
.state('employeeUpdate', {
url: '/employeeUpdate?employeeCode=:param1',
templateUrl: 'pages/employeeUpdate.html',
controller: 'employeeUpdateCtrl',
resolve: {
employeeGatherAll: ['$http', function ($http) {
return $http.jsonp("webserviceSite&procedureName=wsEmployeeGatherAll 'param','param'&callback=JSON_CALLBACK")
.success(function (response) {
return (response)
}).error(function (response) {
console.log("failed");
});
}],
employeeSelectByCode: ['$http','$location', function ($http, $location) {
var employeeCode = $location.search().employeeCode
return $http.jsonp("webServiceSite&procedureName=wsEmployeeSelectByCode 'paramet','parame','" + employeeCode + "'&callback=JSON_CALLBACK")
.success(function (response) {
return (response)
}).error(function (response) {
console.log("failed");
});
}]
}
})
.state('employeeInsert', {
url: '/employeeInsert',
templateUrl: 'pages/employeeUpdate.html',
controller: 'employeeInsertCtrl',
resolve: {
employeeGatherAll: ['$http', function ($http) {
return $http.jsonp("webServiceSiteUrl&procedureName=wsEmployeeGatherAll 'parametar','parametar'&callback=JSON_CALLBACK")
.success(function (response) {
return (response)
}).error(function (response) {
console.log("failed");
});
}],
}
})
So i have selectView as well , where i list all employees, and on click i go to employeeUpdate where i send code trough url as well , my html employeeUpdate page looks something like this :
<div ng-repeat="employee in employee">
<div class="col-md-4">
<label>Employee code</label>
<input type="text" class="form-control" id="txtEmployeeCode" ng-model='employee.employeeCode' />
</div>
<div class="col-md-4">
<label>Status</label>
<select id="Select3" class="form-control" ng-model="employee.statusCode" ng-options="item.code as item.name for item in employeeGather.status">
<option value="">Select status</option>
</select>
</div>
</div>
And these are the controllers
angular
.module('app')
.controller('employeeUpdateCtrl', ['$scope', 'employeeGatherAll', 'employeeSelectByCode', function ($scope, employeeGatherAll, employeeSelectByCode) {
$scope.employee = employeeSelectByCode.data.employee;
$scope.employeeGather = employeeGatherAll.data
}])
.controller('employeeInsertCtrl', ['$scope', 'employeeGatherAll', function ($scope, employeeGatherAll) {
$scope.employeeGather = employeeGatherAll.data
}])

employee.SelectByCode.data.employee[0] was the soulution , without ng-repeat

Related

Vue.js - Search function for JSON Object

I am new to Vue.js, and I want to add a search function for my site. The data is from an API Call and is displayed using vue.js too.
Display HTML Code:
<div class="row" v-for="items in data">
<div class="col-lg-4 col-md-6" data-toggle="modal" data-target="#exampleModal" user="'items'" #click="sendInfo(items)">
<a href="#" class="latest-product__item">
<div class="latest-product__item__pic">
<img src="img/item_image_placeholder.jpg" alt="">
</div>
<div class="latest-product__item__text">
<h6>{{items.item_name}}</h6>
<div v-for="variant in items.variants">
<div v-for="store in variant.stores">
<span>{{store.default_price}}</span>
</div>
</div>
</div>
</a>
</div>
And here's my Vue.js:
window.onload = function () {
const access_token = "";
new Vue({
el: '#item-data',
data () {
return {
data:[],
selectedUser:'',
itemCart: [],
search:'',
quantity: '',
cartCheckout: []
}
},
mounted () {
axios.get('**api call here**', {
headers : {
Authorization: 'Bearer ' + access_token
},
params: {
limit: 250
}
})
.then((response) => {
// handle success
this.data = response.data.items
console.log(response);
removeLoader();
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
});
},
computed:{
cartItem(){
return store.getters.printCart;
},
count(){
return store.state.cartCount;
},
},
methods:{
sendInfo(items) {
this.selectedUser = items;
},
addCart: function(cartdets){
store.commit('addCart', cartdets);
store.commit('addCount', 1);
}
}
})
}
What I want now is to add a search function to my displayed items. I already added v-model to my input tag. The items are dynamically displayed using vue and I want a search function for specific items.
You could create a computed property, maybe name it something like filteredItems, and make it loop through all of your items and save the items you want to display into an array and then return that array.
Then in your html use a v-for to display the items from filteredItems.

How to add two methods on a #click event using vue.js?

This is my code and i basically want to add CHANGEBUTTONS to the on click event that looks like #click.
<button #click="enviarform2" value="Delete from favorites" style="font-weight: 700;color:#428bca;margin-left:30px;height:30px;border-radius:4px" name="delete" v-else>Delete from favorites</button>
<script>
new Vue({
el:'#app',
data:{
show: true,
paletteid : <?=$palette_id;?>,
action: "add",
action2: "delete",
number: ""
},
methods: {
enviarform: function() {
axios.post('/validarfavorite.php', {
paletteid: this.paletteid,
action: this.action
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
this.number = "Yours plus ";
},
enviarform2: function() {
axios.post('/validarfavorite.php', {
paletteid: this.paletteid,
action2: this.action2
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
this.number = "Minus yours plus ";
},
changebuttons: function() {
this.show = !this.show;
}
}
});
</script>
I have tried with method 1 and method 2 and handler but it didnt work. Hope you know!
You can separate the calls using a ; (or the comma operator):
<button #click="#click="m1(); m2()">my button</button>
<button #click="#click="m1(), m2()">my button</button>
But if your code is used in more than one place, though, the best practice (the "cleanest approach") is to create a third method and use it instead:
<button #click="mOneAndTwo">my button</button>
Demo:
new Vue({
el: '#app',
data: {
message: 'Hello Vue.js!'
},
methods: {
m1: function() { this.message += "m1"; },
m2: function() { this.message += "m2"; },
mOneAndTwo: function() {
/* call two methods. */
this.m1();
this.m2();
}
}
})
<script src="https://unpkg.com/vue"></script>
<div id="app">
<p>{{ message }}</p>
<button #click="m1(); m2()">call two methods using ;</button><br>
<button #click="m1(), m2()">call two methods using ,</button><br>
<button #click="mOneAndTwo">call two methods using a third method</button><br>
</div>
The easiest way to do it is:
<button v-on:click="method1(); method2();">Continue</button>
Cant you simply call the methods inside the functions?

AngularJS: How to create routes with ui-router for my application

I have a problem with my a tag - I have a page that present data according to the GET vars.
For example - /foo.php?opt=1 will show table of cities that each one will go to - /foo.php?city=4 that have table of schools that go to /foo.php?school=4 that show table of students etc..
The problem is that the first time it works - when I choose city it will show me the list of schools and change the url, but when I choose school, it changes the URL but I still see the city table, and only if I press F5 it will show me table students.
This is the code:
odinvite.php:
<?php
if (isset($_GET['city']))
{
include "odbycity.php";
}
else if (isset($_GET['school']))
{
include "odbyschool.php";
}
else
{
include "odshowcities.php";
}
?>
odshowcities.php:
<div ng-controller="allcities">
<button class="btn btn-info" ng-repeat="x in names">
<a href="/odinvite.php?city={{x.areaid}}">
{{x.areaname}}</a>
</button>
</div>
odbyschool.php:
<div ng-controller="odbycity">
<button class="btn btn-info" ng-repeat="x in names">
<a href="/odinvite.php?school={{x.schoolid}}">
{{x.school_name}}</a>
</button>
</div>
MyAngular.js:
var myApp = angular.module('myApp',[]);
myApp.config(function( $locationProvider) {
$locationProvider.html5Mode(true);
});
myApp.controller ('allcities', function ($scope, $http)
{
$http.get("fetch_json_sql.php?option=1")
.then(function (response)
{
$scope.names = response.data.result;
});
console.log($scope.names);
});
myApp.controller ('odbycity', function ($scope, $http, $location)
{
$scope.cityid=$location.search().city;
console.log($scope.cityid);
$http.get("fetch_json_sql.php?option=2&cityid="+$scope.cityid)
.then(function (response)
{
$scope.names = response.data.result;
});
});
myApp.controller ('odbyschool', function ($scope, $http ,$location)
{
$scope.schoolid = $location.search().school;
console.log($scope.schoolid);
$http.get("fetch_json_sql.php?option=4&schoolid="+$scope.schoolid)
.then(function (response)
{
$scope.names = response.data.result;
});
});
What can be the problem?
I tried to make 100% change of the URL - link and it didn't work. just changed the URL without redirect.
Thanks!
You should stop rendering your templates with a backend. AngularJS is for SPA. If you need data provided by a backend try to implement an API e.g. a RESTful API. you need to configure your routes for example like in this runnable demo plnkr. It uses ui-router. Please note, this is just a demo. You should be able to put your logic into that prototype. I prepared all routes you need by using some dummy data. Just include your existing API in the controllers and you should be fine.
var myApp = angular.module("myApp", ['ui.router']);
myApp.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.when("", "/main");
$stateProvider
.state("main", {
url: "/main",
templateUrl: "main.html"
})
.state("main.listSchools", {
url: "/listSchools/:schoolId",
templateUrl: "schools.html"
})
.state("main.listAreas", {
url: "/listAreas/:areaId",
templateUrl: "areas.html"
});
});
myApp.controller('mainMenuController', function ($scope) {
$scope.schools = [{
schoolid: 1,
name: 'Test School 1'
},{
schoolid: 5,
name: 'Test School 5'
},{
schoolid: 11,
name: 'Test School 11'
}];
$scope.areas = [{
areaid: 3,
name: 'Test area 3'
},{
areaid: 7,
name: 'Test area 7'
},{
areaid: 19,
name: 'Test area 7'
}];
});
myApp.controller('listSchoolController', function ($scope, $state) {
$scope.schoolId = $state.params.schoolId;
});
myApp.controller('listAreaController', function ($scope, $state) {
$scope.areaId = $state.params.areaId;
});

"[object object]" shown when double-clicking input

Below is the template I am using for the directive. In code we are
fetching the data from a service in that data we have all the
information of that particular person. And from that data we are
showing only first name, last name and designtion or company
affiliation.
<div ng-if="model" class="entry-added">
<span class="form-control"><b>{{model.fullName}}</b>, <br/><span class="small-font">{{(model.designation)?model.designation:model.companyAffiliation}}</span></span>
<a ng-click="removePerson()" class="action-remove"><i class="fa fa-remove"></i></a>
</div>
<div ng-show="!model" class="input-group">
<input type="text"
class="form-control"
name="{{name}}"
id="{{name}}"
placeholder="{{placeholder}}"
ng-required="{{isRequired}}"
typeahead-on-select = "change($item, $model, $label)"
ng-model="model"
typeahead-min-length="3",
typeahead="suggestion for suggestion in searchEmployees($viewValue)"
typeahead-template-url="typeAheadTemplate.html"
typeahead-loading="searching"
typeahead-editable="false">
<script type="text/ng-template" id="typeAheadTemplate.html">
<a class="ui-corner-all dropdown" tabindex="-1">
<div class="col-md-2"><img class="dropdown-image" ng-src="https://people.***.com/Photos?empno={{match.model.employeeNumber}}"></div>
<div>
<div bind-html-unsafe="match.model.fullName"></div>
<div bind-html-unsafe="match.model.designation"></div>
</div>
</a>
</script>
I am using a custom directive to display a search field. The drop down is displaying [object object].
Directive
// In backend taxDeptContact is a Person type object
/*
Directive code
*/
(function () {
'use strict';
angular.module('treasuryApp.directives').directive('employeeSearch', employeeSearch);
employeeSearch.$inject = ['$resource', '$rootScope', 'ErrorHandler'];
function employeeSearch($resource, $rootScope, ErrorHandler) {
return {
restrict: 'E',
require: '^form',
scope: {
model: "=",
isRequired: '#',
submitted: "=",
onSelect: '&',
name: '#',
index:'#'
},
link: function(scope, el, attrs, formCtrl) {
//set required attribute for dynamically changing validations
scope.searchEmployees = function (searchTerm) {
var users = [];
var myResult = [];
var result = $resource($rootScope.REST_URL + "/user/getEmployees", {term: searchTerm}).query().$promise.then(function (value) {
//console.log(value)
$.each(value, function(i, o) {
users.push(o);
});
return users;
});
return result;
}
scope.removePerson = function() {
scope.model=null;
}
scope.userNotSelectedFromTypeahead = function(name) {
if(undefined === formCtrl[name]) {
return false;
}
return formCtrl[name].$error.editable;
};
scope.change = function(item, model, label) {
scope.model = item
scope.onSelect(
{name: scope.name, person: scope.model});
},
templateUrl: 'app/components/common/directives/employee-search.tpl.html'
};
}
})();
View that is using the directive
<div class="form-group">
<label class="col-sm-3>Tax Dept Contact</label>
<div class="col-sm-4">
<employee-search model="reqCtrl.requestObj.taxDepartmentContact" name="taxDeptContact" is-required="false" submitted="reqCtrl.submitted"/>
</div>
</div>
Image of the error occuring
Looks like this may be your trouble spot
typeahead="suggestion for suggestion in searchEmployees($viewValue)"
suggestion for suggestion is pulling the whole object. Have you tried displaying a particular attribute of suggestion?
For example: if you had a suggestion.name attribute you would write:
typeahead="suggestion.name for suggestion in searchEmployees($viewValue)"
Finally got the answer: I used autocomplete="off" in my directive and thats all
<input type="text" autocomplete="off" />

AngularJS $resource JSON field name conversion

I'm working on an AngularJS project that uses an API to deal with data. Now I'm implementing the 'create' functionality using $resource. Everything was going well except the naming conversion: I use camelCase but the API accepts snake_case only.
Is there a way to automatically convert these keys to snake_case?
Service:
services.factory('Salons', ['$resource',
function ($resource) {
return $resource('/salons/:slug', {
slug: "#slug"
});
}
]);
Controller:
controllers.controller('CreateSalonController', ['$scope', 'Salons',
function ($scope, Salons) {
$scope.submit = function() {
Salons.save(this.salon);
};
}
]);
View:
<form name="salonForm" role="form" ng-submit="submit()">
<div class="form-group">
<label for="salonContactFirstName">First name</label>
<input name="contactFirstName" type="text" class="form-control" id="salonContactFirstName" data-ng-model="salon.contactFirstName" />
</div>
...
I have not found any built-in solution so I implemented one:
A new service:
services.factory('Util', function () {
var Util = {
stringToSnakeCase: function (input) {
return input.replace(/([0-9A-Z])/g, function ($1) {
return "_" + $1.toLowerCase();
});
},
objectKeysToSnakeCase: function (input) {
var output = {};
_.each(input, function (val, key) {
output[Util.stringToSnakeCase(key)]
= _.isObject(val) ? Util.objectToSnakeCase(val) : val;
});
return output;
}
};
return Util;
}
);
And the updated controller:
controllers.controller('CreateSalonController', ['$scope', 'Salons', 'Util',
function ($scope, Salons, Util) {
$scope.submit = function() {
Salons.save(Util.objectKeysToSnakeCase(this.salon));
};
}
]);