materializecss autocomplete onchange - javascript

I am trying to use the materialize autocomplete element
I retrieve properly the autocomplete elements but they don't appear while I enter begining of sentence :
It seemed data is loaded but when I try to refresh the instance (instance.open for instance) if fail.
how could I handle it ?
regards
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css">
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.js"></script>
<div class="row">
<div class="col s12">
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">textsms</i>
<input type="text" id="autocomplete-input" class="autocomplete" onkeypress="valueChange(this);">
<label for="autocomplete-input">Autocomplete</label>
</div>
</div>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('.autocomplete');
var instances = M.Autocomplete.init(elems, {});
});
function valueChange(elem) {
var instance = M.Autocomplete.getInstance(elem);
console.log("search for " + elem.value);
axios.post("<%= test_autocomplete_search_path %>", {
search: elem.value,
authenticity_token: '<%= form_authenticity_token %>',
})
.then(function (response) {
var map = new Object();
for (bcl = 0; bcl < response.data.length; bcl ++) {
map[response.data[bcl].town] = null;
}
if (response.data.length > 0) {
console.log(map);
instance.updateData(map);
instance.open(); FAIL HERE
}
})
.catch(function (error) {
alert(error);
});
};
</script>

Related

Asp.Net Core - How to use the amount of input in the loop with Ajax?

I Have a Input tag in Html :
<div class="form-group col-md-5">
<input asp-for="CountSlide" class="form-control" value="2"/>
<a id="add-slide" class="btn btn-info m-t-5" href="#">Add</a>
</div>
And I Have A Loop in Razor View :
#for (int i = 0; i < count; i++)
{
<div class="form-group">
<input type="file" onchange="readURL(this);" class="form-control">
</div>
}
I want to use the input value in the loop ("count") when the add button is clicked?
NEWEST
You can put your #for code in partial view.
How to use jquery or ajax to update razor partial view in c#/asp.net for a MVC project
You want the following div in #for (int i = 0; i <count; i++) to render elements according to the value in the input, which is impossible.
You only can do it by javascript, not use razor engine.
Related Post: What is the order of execution of the C# in Razor
The simple explanation is that when you can see all the contents of the page, the back-end C# code will no longer be executed.
PRIVIOUS
You can use #count to get the value.
#{
ViewData["Title"] = "Home Page";
int count = 5;
}
<script src="https://code.jquery.com/jquery-2.2.4.js" integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"></script>
<script>
function readURL(url) {
alert(url)
}
function func() {
var get_count = #count;
alert(get_count);
//$.ajax({
// url: "url",
// type: "POST",
// data: {a:"a"},
// success: function (veri) {
// console.log("success");
// },
// error: function (hata, ajaxoptions, throwerror) {
// alert("failed");
// }
//});
}
</script>
<div class="form-group col-md-5">
<input class="form-control" value="2" />
<a id="add-slide" class="btn btn-info m-t-5" href="#" onclick="func()">Add</a>
</div>
<hr />
#for (int i = 0; i < count; i++)
{
<div class="form-group">
<input type="file" onchange="readURL(this);" class="form-control">
</div>
}

using data posted by ajax to node js problem

I'm trying to update my template without refreshing the page by ajax .... and I used two arrays for saving data permanently on front side and I send these two arrays with post method and ajax to my node js... I have some other input in my template but I don't want to send them with ajax ... How to parse them beside
ajax post?
my server
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const multer = require("multer");
const mongoose = require('mongoose');
const path = require("path");
const app = express();
var titlesList = [];
app.use(express.static("public"));
//if we wanna recive data from ajax we have to use this line
// var jsonParser = bodyParser.json();
// parse application/json
app.use(express.json());// add this line
app.use(bodyParser.urlencoded({ extended: false }));
var c = [];
var storage = multer.diskStorage({
destination:function(req,file,cb){
cb(null , "public/upload");
},
filename:function(req,file,cb){
cb(null , file.filename + '-' + Date.now() + path.extname(file.originalname));
}
});
var upload = multer ({
storage:storage
})
mongoose.connect("mongodb://localhost:27017/landingDb" , {useNewUrlParser : true} , { useUnifiedTopology: true } );
const courseSchema = new mongoose.Schema ({
courseTitle : String,
courseSubtitle : String,
coursreAuthor : String,
coursePrice : Number,
courseVideo : Object,
courseSpecs : Array,
courseTitles : Array,
courseValidation : Number,
courseTags : Array
});
const Courses = mongoose.model("Courses" ,courseSchema );
app.set("view engine", "ejs");
app.get("/cp" , function(req , res){
res.render("cp");
});
app.post("/cp" , upload.single("c_upload") , function(req , res){
var c_titles = [];
const c_specs = JSON.stringify(req.body.specs);
const file = req.file;
const c_title = req.body.c_title;
const c_subtitle = req.body.c_subtitle;
const c_creator = req.body.c_creator;
const c_price = req.body.c_price;
console.log(file);
console.log(JSON.stringify(req.body.titles));
console.log(JSON.stringify(req.body));
if(req.body.submitcp == "submitCp"){
console.log(file);
const courses = new Courses({
courseTitle:c_title,
courseSubtitle:c_subtitle,
courseAuthor : c_creator,
coursePrice : c_price,
courseVideo : file,
courseTitles : c_titles,
courseSpecs : c_specs,
courseValidation : 0
});
courses.save();
}
});
app.listen(3000, function () {
console.log("running");
});
my html
<%- include('header'); -%>
<div class="container-fluid">
<div class="row">
<div dir="rtl" class="col-md-6 cp_main_div">
<form action="/cp" enctype="multipart/form-data" class="titlesForm" id="form" method="post">
<div class="col-md-12">
<div class="form-group">
<label for="exampleInputEmail1">عنوان دوره</label>
<input name="c_title" type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="...">
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="exampleInputEmail1">توضیحات مختصر دوره</label>
<input name="c_subtitle" type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="...">
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="exampleInputEmail1">سازنده دوره</label>
<input name="c_creator" type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="...">
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="exampleInputEmail1">قیمت دوره</label>
<input name="c_price" type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="...">
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="exampleFormControlFile1">آپلود ویدیو معرفی</label>
<input name="c_upload" type="file" class="form-control-file videoup" id="fileupload">
</div>
</div>
<div class="col-md-12" >
<div class="c_preview_div">
<div class="video_play"></div>
<video class="c-preview-video">
<source src="assets/gm2.mp4" type="video/mp4">
Your browser does not support HTML video.
</video>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="exampleInputEmail1">نوع دوره</label>
<select name="c_type" class="form-control form-control-lg">
<option>وبینار</option>
<option>دوره آنلاین</option>
<option>دوره آفلاین</option>
<option>ورکشاپ</option>
<option>دوره فیزیکی</option>
</select>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="exampleInputEmail1">عنوان های دوره</label>
<input name="titlesInput" id="titlesInp" type="text" class="form-control cp_input_titles" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="...">
</div>
<button id="title_submit" name="addTitles" value="addtitles" type="clickspecs_submit" class="btn btn-primary mb-2 add_titles">+</button>
<div style="width: 100%; height: 100%;" id="showTitles">
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="exampleInputEmail1">مشخصات دوره</label>
<input name="specsInput" id="c_specs" type="text" class="form-control cp_input_titles" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="...">
</div>
<button id="specs_submit" name="addSpecs" value="addspecs" type="click" class="btn btn-primary mb-2 add_titles">+</button>
<div style="width: 100%; height: 100%;" id="showSpecs">
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="exampleInputEmail1">تگ ها</label>
<select name="c_type" class="form-control form-control-lg">
<option>وبینار</option>
<option>دوره آنلاین</option>
<option>دوره آفلاین</option>
<option>ورکشاپ</option>
<option>دوره فیزیکی</option>
</select>
</div>
</div>
<div class="col-md-12">
<button type="submit" name="submitcp" value="submitCp" id="submitpostCp" class="btn btn-primary btn-lg btn-block">send</button>
</div>
</div>
</form>
<!-- <iframe id="uploader_iframe" name="uploader_iframe" style="display: none;"></iframe> -->
</div>
</div>
</div>
</body>
<footer>
</footer>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous">
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous">
</script>
<script charset="utf-8" src="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/owl.carousel.min.js"></script>
<script type="text/javascript" charset="utf-8" src="script.js"></script>
<script type="text/javascript" charset="utf-8" src="sort.js"></script>
<script type="text/javascript" src="lightslider.js"></script>
</html>
my ajax call
var titlesLis = [];
var specsLis = [];
document.getElementById("form").addEventListener("submit", function (e) {
e.preventDefault();
e.stopPropagation();
//check what btn submit and push to item to array
if (e.submitter.id == "title_submit") {
var titlesInp = $(".cp_input_titles").val();
titlesLis.push(titlesInp);
}
//check what btn submit and push to item to array
if (e.submitter.id == "specs_submit") {
var specsInp = $("#c_specs").val();
specsLis.push(specsInp);
}
//check what btn submit and remove item from array
//check what btn submit and delete the item from view
if (e.submitter.id == "delete_specs") {
if(e.submitter.id >="0"){
specsLis.splice(e.submitter.id , 1);
}
$("#" + 'specs' + e.submitter.value).remove();
showspecItems();
}
//check what btn submit and remove item from array
//check what btn submit and delete the item from view
if (e.submitter.id == "delete_titles") {
if(e.submitter.id >="0"){
titlesLis.splice(e.submitter.id , 1);
}
$("#" + 'titles' + e.submitter.value).remove();
showtitleItems();
}
var data = {};
data.titles = titlesLis;
data.specs = specsLis;
//ajax call
$.ajax({
type: 'post',
url: '/cp',
data: JSON.stringify(data),
contentType: 'application/json',
xhrFields: {
withCredentials: false
},
headers: {
},
success: function (data) {
console.log('Success');
console.log(data);
//check what btn submit and delete the item from view
if (e.submitter.id == "title_submit") {
showtitleItems();
}
if (e.submitter.id == "specs_submit") {
showspecItems();
}
},
error: function () {
console.log('We are sorry but our servers are having an issue right now');
}
})
function showtitleItems() {
$("#showTitles").empty();
for (var i = 0; titlesLis.length > i; i++) {
$("#showTitles").append('<div id="' + 'titles' + i + '" class="TSShow titlesShow"><button name="deleteTitles" value="' + i + '" type="submit" id="delete_titles">-</button><h4>' + titlesLis[i] + '</h4></div>');
}
}
function showspecItems() {
$("#showSpecs").empty();
for (var i = 0; specsLis.length > i; i++) {
$("#showSpecs").append('<div id="' + 'specs' + i + '" class="TSShow specsShow"><button name="deleteSpecs" value="' + i + '" type="submitz" id="delete_specs">-</button><h4>' + specsLis[i] + '</h4></div>');
}
}
})

Unable to load a Knockout Component - Unknown template value: [object Object]

This is how I am using the component and sending the parameters using a Custom Element:
<div class="container" data-bind="with: DevoteeList">
<div class="row" style="padding: 10px;">
<div class="col-md-8"></div>
<div class="col-md-4">
<ko-pager params="Data: Devotees,
Modifier: $parent.DevoteeModifier,
PageCount: DevoteesPageCount(),
Url: '#Url.Action("SelectDevotees", "Devotee", new { a = 1 })'"></ko-pager>
</div>
</div>
This is how I am defining a Knockout Component. It is a Pager that I want to use at few places. But, I am receiving the error: Uncaught Error: Unable to process binding "with: function (){return SelectDevotees }"
Message: Unable to process binding "with: function (){return DevoteeList }"
Message: Unable to process binding "component: function () { return l }"
Message: Component 'ko-pager': Unknown template value: [object Object]
ko.components.register('ko-pager', {
viewModel: function (params) {
var self = this;
self.currentPage = ko.observable(1);
self.pages = ko.observableArray([]);
self.PageCount = ko.observable(params.PageCount);
//self.currentPage.subscribe(function (nv) {
// self.GetPage(self.parent);
//});
self.GetPages = function () {
for (var i = 1; i <= params.PageCount ; i++) {
self.pages.push(i);
}
return self.pages;
};
self.FirstPage = function () {
self.GetPage(1);
};
self.PrevPage = function () {
if (self.currentPage() > 1) {
var pn = self.currentPage() - 1;
self.GetPage(pn);
}
};
self.LastPage = function () {
self.GetPage(params.PageCount);
};
self.NextPage = function () {
if (self.currentPage() < params.PageCount) {
var pn = self.currentPage() + 1;
self.GetPage(pn);
}
};
self.GetPage = function (pg) {
if (pg == null)
pg = self.currentPage();
else
self.currentPage(pg);
var url = params.Url + '&pageNumber=' + pg;
$.get(url, function (data) {
var t = ko.mapping.fromJS(data);
if (params.Modifier) {
params.Modifier(t);
}
params.Data(t());
});
};
},
template: { element: document.getElementById('ko-ajax-pager') }
});
<div id="ko-ajax-pager" style="display: none;">
<div class="row" style="padding: 10px;" data-bind="visible: PageCount > 1">
<div class="col-md-1"></div>
<div class="col-md-2">
<input type="button" value="First" class="btn" data-bind="click: FirstPage" />
</div>
<div class="col-md-2">
<input type="button" value="Prev" class="btn" data-bind="click: PrevPage" />
</div>
<div class="col-md-2">
<select data-bind="options: GetPages(), value: currentPage, event: { change: GetPage(null) }">
</select>
</div>
<div class="col-md-2">
<input type="button" value="Next" class="btn" data-bind="click: NextPage" />
</div>
<div class="col-md-2">
<input type="button" value="Last" class="btn" data-bind="click: LastPage" />
</div>
<div class="col-md-1"></div>
</div>
</div>
Can someone please figure out, what is wrong?

AngularJS move part of Controller to Service

Consider the following code.
HTML:
<!doctype html>
<html ng-app="todoApp">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="/css/bootstrap.min.css" rel="stylesheet">
<link href="/css/overlay-control.css" rel="stylesheet">
<link href="/css/list-control.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!--<script src="/js/Services/UserService.js"></script>-->
<script src="/js/Controllers/MainController.js"></script>
<!--<script src="/js/Controllers/UserController.js"></script>-->
<script src="/js/bootstrap.min.js"></script>
</head>
<body ng-controller="MainController as myControl">
<div id="overlaycover" ng-click="myControl.showUpd(0)"></div>
<div id="overlaybox">
<div class="col-md-12">
<h4>Update:</h4>
<form ng-submit="myControl.updTodo()">
<div class="form-group">
<label for="updContent">Note:</label>
<textarea rows="5" cols="30" class="form-control" id="updContent" name="updContent" ng-model="noteupd.content"></textarea>
</div>
<div class="form-group">
<label for="updDeadline">Deadline (format YYYY-MM-DD HH:MM:SS):</label>
<input type="text" class="form-control" id="updDeadline" name="updDeadline" ng-model="noteupd.deadline" />
</div>
<div class="checkbox">
<label>
<input type="checkbox" id="updCompleted" name="updCompleted" ng-model="noteupd.completed" /> - Completed
</label>
</div>
<div class="form-group">
<input type="hidden" id="updID" ng-model="noteupd.id" /><br/>
<button type="submit" class="btn btn-info">Update</button>
</div>
</form>
Click utside the square to close.
</div>
</div>
<div class="container">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12" id="listDiv">
<h1>Todo-list:</h1>
<p>
<img src="/images/legend-normal.png"> - Unfinished 
<img src="/images/legend-completed.png"> - Finished 
<img src="/images/legend-late.png"> - Late
</p>
<table class="table" id="list-table">
<tr>
<th>Note:</th>
<th>Author:</th>
<th>Project:</th>
<th>Created:</th>
<th>Deadline:</th>
<th colspan="2">Modify:</th>
</tr>
<tr ng-repeat="todo in myControl.todos" ng-class="rowClass(todo.completed, todo.deadline)">
<td> {{ todo.content }} </td>
<td> {{ todo.user }} </td>
<td> {{ todo.project }} </td>
<td> {{ todo.created }} </td>
<td> {{ todo.deadline }} </td>
<td><button type="button" class="btn btn-info" ng-click="myControl.showUpd(todo.id)">Update</button></td>
<td><button type="button" class="btn btn-danger" ng-click="myControl.delTodo(todo.id)">Delete</button></td>
</tr>
</table>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12" id="formDiv">
<h3>Add new note:</h3>
<form ng-submit="myControl.addTodo()">
<div class="form-group">
<label for="newUser">User:</label>
<select ng-model="noteadd.user" class="form-control" id="newUser" name="newUser">
<option ng-repeat="user in myControl.users" value="{{ user.id }}">{{ user.name }}</option>
</select><br/>
</div>
<div class="form-group">
<label for="newProject">Project:</label>
<select ng-model="noteadd.project" class="form-control" id="newProject" name="newProject">
<option ng-repeat="project in myControl.projects" value="{{ project.id }}">{{ project.name }}</option>
</select><br/>
</div>
<div class="form-group">
<label for="newContent">Note:</label>
<textarea rows="5" cols="30" ng-model="noteadd.content" class="form-control" id="newContent" name="newContent"></textarea><br/>
</div>
<div class="form-group">
<label for="newDeadline">Deadline (format YYYY-MM-DD HH:MM:SS):</label>
<input type="text" ng-model="noteadd.deadline" class="form-control" id="newDeadline" name="newDeadline" /><br/>
</div>
<div class="form-group">
<button type="submit" class="btn btn-info">Add</button>
</div>
</form>
</div>
</div>
</body>
</html>
AngularJS Controller:
angular.module('todoApp', []).controller('MainController', function($scope, $http) {
var thisApp = this;
$scope.noteadd = {};
var noteadd = $scope.noteadd;
$scope.noteupd = {};
var noteupd = $scope.noteupd;
// Get all notes:
$http({method : 'GET', url : 'http://localhost:8000/notes'})
.then (function(response) {
thisApp.todos = response.data;
}, function() {
alert("Error getting todo notes");
});
// Get all users:
$http({method : 'GET',url : 'http://localhost:8000/users'})
.then(function(response) {
thisApp.users = response.data;
}, function() {
alert("Error getting users");
});
// Get all projects
$http({method : 'GET', url : 'http://localhost:8000/projects'})
.then(function(response) {
thisApp.projects = response.data;
}, function() {
alert("Error getting projects");
});
// Add note to database
thisApp.addTodo = function(noteadd)
{
$http({
method : 'PUT',
url : 'http://localhost:8000/notes',
data : $.param($scope.noteadd),
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function(response) {
location.reload();
}, function() {
alert("Couldn't add note. Please try again!");
});
};
// Hide note by setting removed to 1
thisApp.delTodo = function(noteID)
{
var r = confirm("Are you sure?");
if (r == true) {
var noteObj = JSON.parse('{"id":' + noteID + '}'); // JSON for req
$http({
method : 'DELETE',
url : 'http://localhost:8000/notes',
data : $.param(noteObj),
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function(response) {
location.reload();
}, function() {
alert("Couldn't delete note. Please try again!");
});
}
};
// Show overlay with form for updating a note
thisApp.showUpd = function(noteID)
{
var overlaycover = document.getElementById("overlaycover");
var overlaybox = document.getElementById("overlaybox");
overlaycover.style.opacity = .65;
if(overlaycover.style.display == "block" || noteID == 0){ // For toggling overlay
overlaycover.style.display = "none"; // Hide div overlaycover
overlaybox.style.display = "none"; // Hide div overlaybox
} else {
$http({method : 'GET', url : 'http://localhost:8000/notes/' + noteID})
.then (function(response) {
noteupd.content = response.data.content; // Update fields in form
noteupd.deadline = response.data.deadline;
noteupd.id = response.data.id;
if (response.data.completed == 1) {
noteupd.completed = true;
} else {
noteupd.completed = false;
}
overlaycover.style.display = "block"; // Show div overlaycover
overlaybox.style.display = "block"; // Show div overlaybox
}, function() {
alert("Error getting todo note");
});
}
}
// Update a note
thisApp.updTodo = function(noteupd)
{
$http({
method : 'POST',
url : 'http://localhost:8000/notes',
data : $.param($scope.noteupd),
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function(response) {
location.reload();
}, function() {
alert("Couldn't add note. Please try again!");
});
}
// Check if deadline passed for each note in list
$scope.rowClass = function(completed, deadline)
{
var nowTime = Math.floor(Date.now()/1000);
var deadTime = new Date(deadline);
var deadUTC = Math.floor(deadTime/1000);
if (completed == 1) {
return "success"; // Note is completed
} else if (deadUTC < nowTime) {
return "danger"; // Note is not completed, deadline passed
} else {
return "active"; // Note is not completed, still time left
}
}
});
What I would like to do is to move all $http-calls to a service instead of having them in the controller like I have it now. I have searched the internet but I don't really understand the solutions i've found there.
Second, in several functions, as you can see, I use location.reload();. I would like to use ng-bind instead, but as the sam, I don't understand how this works.
Can someone please explain how I should do these two things?
Ok , let's for example create a Users factory and put all Users api related stuff inside:
'use strict';
angular
.module('todoApp')
.factory('Users', factory);
function factory($http) {
var service = {
get: get,
//edit: edit ...
};
return service;
function get() {
return $http({method : 'GET',url : 'http://localhost:8000/users'})
.then(function(response) {
return response.data;
});
}
//function edit(user) {
// return $http({method : 'PUT...
//}
}
What you have to do next is inject that factory wherever you want to call it.
So in your controller you essentially have to do this:
angular.module('todoApp', [])
.controller('MainController', function($scope, Users) {
//.....
function getUsers() {
Users.get().then(function(data){
thisApp.users = response.data;
}, function() {
alert("Error getting users");
});
}
getUsers();
//...
Repeat the same by creating the appropriate services for notes and projects.
To not bloat the main app.js move this services to seperate files, users.service.js etc..
I would also advise you to move the controllers to seperate files too.
Just be careful:
this is a module creation
angular.module('todoApp', [])
You create a module once.
to attach a service/factory/controller/anything, when you are in that separate file, to that module you use this:
angular.module('todoApp').anything
Second, I assume you use location.reload to update the view with the new data.
Let's say you edit/delete a User. Instead of reloading the page, call getUsers() in the then() of put/delete/create User.
Hope it makes sense to you!
PS: This styleguide by John Papas have been very helpful to me, I suggest you give it a read !
I've already used service factory solution for such kind of problem.
angular.module('data-service').factory('dataService', ['$http',function ($http) {
var url = 'http://localhost:8000/';
return {
getData: function(type) {
return $http({method : 'GET', url : url + type});
},
allData: function() {
return $q.all({
notes: this.getData('notes'),
users: this.getData('users'),
projects: this.getData('projects')
});
}
}
}]);
usage:
dataService.getData('notes').then(function (data) { ... });
also you can use angular promise $q.
dataService.allData().then(function(data) { /* data.notes, data.users, data.projects */ }

Use CKeditor instance in Vue.js

I am trying to implement CKeditor in my Laravel-backoffice which build its views with Vue.js
In this form I want to replace the "textarea" with name="ckeditor1" with a texteditor
<form method="POST" v-on="submit: onSubmitForm">
<div class="col-md-4">
<h1>Pagina: #{{ page.name }}</h1>
<h2>Pagina algemeen</h2>
<div class="form-group">
<label for="name">
Name
<span class="error" v-if="! page.name">*</span>
</label>
<input type="text" name="name" id="name" class="form-control" v-model="page.name">
</div>
<ul class="nav nav-tabs">
<li class="" v-repeat="page.translations" v-class="active: language == defaultLanguage"><a
data-toggle="tab" href="##{{ language }}">#{{ language }}</a></li>
</ul>
<div class="tab-content">
<div v-repeat="page.translations" id="#{{ language }}" class="tab-pane fade in "
v-class="active: language == defaultLanguage">
<h2>Pagina inhoud</h2>
<div class="form-group">
<label for="name">
Titel
</label>
<input type="text" name="title_#{{ language }}" id="title_#{{ language }}"
class="form-control" v-model="title">
</div>
<div class="form-group">
<label for="content">
Inhoud
</label>
<textarea name="ckeditor1" id="content_#{{ language }}"
class="form-control editor" v-model="content"></textarea>
</div>
<h2>Seo</h2>
<div class="form-group">
<label for="meta_keywords">
Meta keywords
</label>
<input type="text" name="meta_keywords_#{{ language }}"
id="meta_keywords_#{{ language }}" class="form-control"
v-model="meta_keywords">
</div>
<div class="form-group">
<label for="meta_decription">
Meta description
</label>
<textarea name="meta_description_#{{ language }}"
id="meta_description_#{{ language }}" class="form-control"
v-model="meta_description"></textarea>
</div>
<input type="hidden" name="page_id_#{{ language }}" id="page_id_#{{ language }}"
class="form-control" v-model="page_id" value="#{{ pageId }}">
</div>
</div>
<div class="form-group" v-if="! submitted">
<button type="submit" class="btn btn-default">
Opslaan
</button>
</div>
</div>
</form>
The #{{ }} fields are loaded and filled with json call and vue.js but there is no problem cause all fields are filled perfectly as needed. The problem is just the initializing of my editor.
This is where I get my data:
Vue.http.headers.common['X-CSRF-TOKEN'] = document.querySelector('#token').getAttribute('value');
var pages = new Vue({
el: '#page',
data: {
pageId: document.querySelector('#page-id').getAttribute('value'),
pageTitle: 'Pagina',
page: [],
submitted: false,
defaultLanguage: 'nl',
errors: false
},
ready: function() {
this.fetch();
},
methods: {
fetch: function() {
this.$http.get('/api/pages/' + this.pageId, function(response) {
this.page = response;
});
},
onSubmitForm: function(e) {
e.preventDefault();
this.submitted = true;
this.errors = false;
if(this.pageId == 0) {
this.$http.post('/api/pages/', this.page, function (response) {
if (response.errors.length) {
this.errors = response.errors;
this.submitted = false;
return;
}//endif
this.submitted = false;
window.location.href = '/admin/pages';
});
}
else
{
this.$http.put('/api/pages/' + this.pageId, this.page, function (response) {
if (response.errors.length) {
this.errors = response.errors;
this.submitted = false;
return;
}//endif
this.submitted = false;
window.location.href = '/admin/pages';
});
}
}
}
});
UPDATE -> SOLVED
By adding Vue.nextTick I can initialize an editor. I added a class 'editor' to every textarea I want it to be an editor and then find all id's from the textareas with class="editor".
fetch: function() {
this.$http.get('/api/pages/' + this.pageId, function(response) {
this.page = response;
Vue.nextTick(function () {
$('textarea.editor').each(function(){
CKEDITOR.replace(this.id);
});
});
});
},
By adding Vue.nextTick I can initialize an editor. I added a class 'editor' to every textarea I want it to be an editor and then find all id's from the textareas with class="editor".
fetch: function() {
this.$http.get('/api/pages/' + this.pageId, function(response) {
this.page = response;
Vue.nextTick(function () {
$('textarea.editor').each(function(){
CKEDITOR.replace(this.id);
});
});
});
}
I am also using CKeditor with laravel-vue. You just need to set and get data with CKeditor for basic thing.
This is my main.html file in which i need CKeditor.
<div class="row">
<div class="col-md-2">
<label for="body" >Mail Body :</label>
</div>
<div class="col-md-10" >
<textarea class="ckeditor" id="body" rows="5" cols="70" name="body" v-model="template.body" ></textarea>
</div>
</div>
After that i initialize my CKeditor value in app.js file
var vm = this;
axios.post('/fetchEmailTemplate', {
'template_id' : template_id
}).then(function (response) {
vm.template = response.data.emailTemplate;
CKEDITOR.instances['body'].setData(vm.template.body);
}).catch(function (error) {
console.log(error);
setNotification(error, "danger");
});
If I'm not mistaken ckeditor replaces the original textarea by a custom template. So what you see within ckeditor will not be put into your messageArea textarea automatically. That's why you don't see any changes to your model. So, for making changes you need to replace updated text before submit in app.js file like below.
this.template.body = CKEDITOR.instances['body'].getData();

Categories

Resources