I have the following angular factory and controller.
var app = angular.module("carForm", []);
app.factory("dataService", ['$http', function getData($http) {
function getCars(){
return $http({
method: 'GET',
url: '/data.json'
}).then(function (response){
console.log(response.data);
return response.data
},function (error){
console.log("product error");
})
};
return { getCars : getCars }
}]);
app.controller("dataSort", ['dataService', '$scope', function(dataService, $scope) {
dataService.getCars().then(function(response){
cars = response;
$scope.make = [];
for (key in cars){
item = cars[key];
console.log(item);
$scope.make.push(item);
}
$scope.model = [];
for (key in cars[$scope.selectMake]){
item = cars[item][key_2]
$scope.model.push(item)
}
})
search = function(cars){
cars[$scope.selectMake][$scope.selectModel][$scope.selectType]
}
}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div class="col-12" ng-contoller="dataSort">
<div class="row" style="text-align: center;">
<div class="form-group col-6">
<label for="inputState">Make</label>
<select id="inputState" class="form-control">
<option ng-model="selectMake" selected>Select make</option>
<option ng-repeat="item in make">{{ item }}</option>
</select>
</div>
<div class="form-group col-6">
<label for="inputState">Model</label>
<select id="inputState" class="form-control">
<option ng-model="selectModel" selected>Select model</option>
<option ng-repeat="item in model">{{ model }}</option>
</select>
</div>
<div class="form-group col-3">
<label for="inputState">Type</label>
<select id="inputState" class="form-control">
<option ng-model="selectType"selected>Select make type</option>
<option ng-repeat="item in type">{{ model }}</option>
</select>
</div>
</div>
</div>
I don't believe either factory or controller are running. Nothing is logged in console, neither the data or the error message. Angular is properly linked to my form as there is no {{ }} also the ng app is declared at the top of the html in the body tag using ng-app="carForm". The JS page is correctly linked to the html as when I console.log outside the angular function it prints. Angular is loaded before my JS script in the head tag, I cant figure out what I'm doing wrong.
Your factory is uncorrected, because you didn't pass your function in return
Right way to make a factory
app.factory("dataService", ['$http', function($http) {
var x = {};
return x;
}]);
But even you change the code it's not work on your controller because
you want to return response.data in $http as promise and this not happens, in
the case you need $q as injection in your service.
var app = angular.module("carForm", []);
app.factory("dataService", ['$http', '$q', function ($http, $q) {
var factory = {}
factory.sample = function() {
console.log("in factory!");
return [1,2,3]
}
factory.getCars = function() {
var deferred = $q.defer();
$http.get("api").then(function(response){
deferred.resolve(response.data);
})
return deferred.promise;
}
return factory;
}]);
app.controller("dataSort", ['dataService', '$scope', function(dataService, $scope) {
$scope.items = dataService.sample();
//uncomment when your api was ready
//dataService.getCars().then(function(response){
// console.log(response);
//})
}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="carForm" ng-controller="dataSort">
<ul>
<li ng-repeat="item in items">{{item}}</li>
<ul>
</div>
Your factory is not correctly implemented Please change it like this.
app.factory("dataService", ['$http', function($http) {
function getCars(){
return $http({
method: 'GET',
url: '/data.json'
}).then(function (response){
console.log(response.data);
return response.data
},function (error){
console.log("product error");
})
};
return { getCars : getCars }
}]);
Related
Let says I have a select tag with a specific id and multiples option. Then below, I want to display partial view base on the selected . I think of using something as if else statement but I don't know how to gain the value of that select with c#.
My thought about this is like this
<select id="selectItem">
<option value="A">A</option>
<option value="B">A</option>
<option value="C">A</option>
</select>
#if ('selectItem' == "A"){
<partial name="..."/>
}
you can do it with js,here is a demo:
Controller(Test):
public IActionResult Index()
{
return View();
}
public IActionResult Partial()
{
return PartialView("Partial1");
}
Partial1:
<h1>Partial1</h1>
Index.cshtml:
<select id="selectItem">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
<div id="PartialContent"></div>
js:
<script>
$(function () {
getPartial();
});
$("#selectItem").change(function () {
getPartial();
});
function getPartial() {
if ($("#selectItem").val() == "C") {
$.ajax({
type: 'GET',
url: "/Test/Partial",
dataType: 'html', //dataType - html
success: function (result) {
//Create a Div around the Partial View and fill the result
$('#PartialContent').html(result);
}
});
}else {
$('#PartialContent').html("");
}
}
</script>
result:
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 5 years ago.
While the VueJS data that is populated from Axios Get method and can be confirmed by outputting the data into console, I am not able to access the data from the front end.
Here is my sample JSON ouput
{
"locations" : {
"items" : ["abc","def","ghi"],
"selectedLocation" : ""
},
"categories" : {
"items" : {
"doctor" : ["test", "test2", "test3"],
"management" : ["test1","test2","test3"]
},
"subcategories":[],
"selectedCategory":"",
"selectedSubCategory":""
}
Here is my Front End Code
<form id="vueAppJobSearchPanel" class="offset-top-10 offset-sm-top-30" action="/job-search">
<div class="group-sm group-top">
<div style="max-width: 230px;" class="group-item element-fullwidth">
<div class="form-group">
<select v-model="locations.selectedLocation" id="form-filter-location" name="loc" data-minimum-results-for-search="Infinity" class="form-control">
<option value="">{{global.job_search_panel.placeholder_title_location}}</option>
<option v-for="location in locations.items" :value="location">${location}</option>
</select>
</div>
</div>
<div style="max-width: 230px;" class="group-item element-fullwidth">
<div class="form-group">
<select v-model="categories.selectedCategory" id="form-filter-location" name="cat" data-minimum-results-for-search="Infinity" class="form-control">
<option value="">{{global.job_search_panel.placeholder_title_category}}</option>
<option v-for="(category_obj, category) in categories.items" :value="category">${category}</option>
</select>
</div>
</div>
</div></form>
Here is my VueJS and AXIOS code
const vm = new Vue({
el: '#vueAppJobSearchPanel',
delimiters: ['${', '}'],
data: {
test: {
"items" : ["abc","def","ghi"],
"selectedLocation" : ""
},
locations : {},
categories : {}
},
mounted(){
this.loadDropDown();
},
methods: {
loadDropDown : function() {
let modelName = "CustomModule1";
let apiUrl = '/api/' + modelName + '/getFields';
axios.get(apiUrl)
.then(function (response) {
this.locations = constructLocationDropDownValues(response, modelName);
this.categories = constructCategorySubCategoryDropDownValues(response, modelName);
})
.catch(function (error) {
console.log(error);
});
}
}});
this.locations inside the loadDropDown function return a valid JSON. However the JSON is not passed to the front end (i.e. HTML). When I tried to output "locations" it will return an empty {}
Ideas? Thank you
The problem is with 'this' inside the axios callback. You should use arrow function to keep the context
axios
.get(apiUrl)
.then(response => {
this.locations = constructLocationDropDownValues(response, modelName)
this.categories = constructCategorySubCategoryDropDownValues(response,modelName)
})
.catch(function (error) {
console.log(error)
})
I have a application running with a flask backend and angular frontend. Apparently when a wrong password is entered i want to show a error message. I have tried out ng-show and ng-if both nothing seems to work.
This is the html for my login page -
<div layout="column" layout-align="center center" class="">
<img class="logo" ng-src="assets/images/logo.png">
<h1 class="md-display-2 login-heading">Login to Bassa</h1>
<div layout="row">
<md-input-container>
<label>User name</label>
<input type="text" ng-model="user.user_name"/>
</md-input-container>
<md-input-container>
<label>Password</label>
<input type="password" ng-model="user.password" ng-enter="login()"/>
</md-input-container>
<br>
</div>
<div>
<md-button class="md-raised md-primary" ng-click="login()">Login</md-button>
<md-button class="md-raised md-primary" ng-click="signup()">Signup</md-button>
</div>
And this is the login controller -
(function(){
'use strict';
angular
.module('app')
.controller('LoginCtrl', ['$scope', '$state', 'UserService', LoginCtrl]);
function LoginCtrl($scope, $state, UserService) {
$scope.user = {};
$scope.incorrectCredentials = false;
$scope.login = function(){
UserService.login($scope.user, function(status) {
if (status){
$state.go('home.dashboard');
} else {
$scope.incorrectCredentials = true;
}
});
};
$scope.signup = function() {
$state.go('signup');
};
UserService.removeToken();
}
})();
When the incorrectCredentials becomes true , i want to show a message.
After logging the User service -
var login = function(credentials, cb) {
var $http = $injector.get('$http');
return $http({
method: 'POST',
url: BassaUrl + '/api/login',
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]));
return str.join('&');
},
data: credentials,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function (response) {
setToken(response.headers()['token']);
setName(credentials.user_name);
setAuthLevel(response.data.auth);
console.log(response);
cb(true);
}, function(error){
console.log("hello i am here")
cb(false);
});
};
I received a response log -
Object {data: "<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final/…ead-protected or not readable by the server.</p>↵", status: 403, config: Object, statusText: "FORBIDDEN"}
It isn't entering the error block , which prevents me from prompting wrong password message.
It was actually my own fault. My custom Interceptor simply swallowed authentication errors.
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
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" />