When i put
<script>
var renderCaptchas = function() {
grecaptcha.render(this, {
'sitekey' : {{ google_recaptcha_site_key }}
});
};
var onloadCaptchaCallback = function () {
Array.prototype.forEach.call(document.querySelectorAll('.g-recaptcha'),
renderCaptchas);
};
</script>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCaptchaCallback&render=explicit" async defer></script>
I have this error :
reCAPTCHA couldn't find user-provided function: onloadCaptchaCallback
The function is yet well defined ...
If i remove
grecaptcha.render(this, {
'sitekey' : {{ google_recaptcha_site_key }}
});
Then it finds the callback ...
I use the Google ReCaptcha v2, with the checkbox "mode".
There is something strange in your loop for me and grecaptcha.render(this !? this = renderCaptchas ... no !? So the element you want to render is not good because it is not a valid html container.
<script>
var renderCaptchas = function(element) {
grecaptcha.render(element, {
'sitekey' : 'google_recaptcha_site_key'
});
};
</script>
or something like :
<script>
var onloadCaptchaCallback = function () {
[].forEach.call(document.querySelectorAll('.g-recaptcha'), function(element){
grecaptcha.render(element, {
'sitekey' : 'google_recaptcha_site_key'
});
}
});
};
</script>
How to loop over document.querySelectorAll :
How to loop through selected elements with document.querySelectorAll
Related
I have a non-SPA web app that has Vue components and that works very well. However, I am looking for a way to load HTML that contains Vue via an external API.
So, I simply make a call to /ajax/dialogbox/client/add which is returning HTML containing Vue components, like:
<h1>Add client</h1>
<div>My static content</div>
<my-component></my-component>
but obviously <my-component></my-component> does not do anything.
In Angular 1 I was using $compile service to compile the HTML before output.
Is there a way to do the same in Vue?
There is a compile function available in Vue that compiles templates to render functions. Using the compiled functions requires a little more detail than you have provided (if you needed to use the returned template with data, for example), but here is one example.
console.clear()
Vue.component("my-component",{
template: `<h1>My Component</h1>`
})
const template = `
<div>
<h1>Add client</h1>
<div>My static content</div>
<my-component></my-component>
</div>
`
new Vue({
el: "#app",
data:{
compiled: null
},
mounted(){
setTimeout(() => {
this.compiled = Vue.compile(template)
}, 500)
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script>
<div id="app">
<component :is="compiled"></component>
</div>
Note that in the example, I wrapped your example template in a div tag. Vue requires that there is on a single root element for a Vue or component.
After many hours, I managed to pass some properties to the component to be compiled.
In the HTML body:
<!-- some where in the HTML body -->
<div id="vCard2">
<component :is="compiled"></component>
</div>
<script>
var vmCard2 = new Vue({
el: '#vCard2',
data: {
compiled: null,
status: ''
},
methods: {
show: function () {
// macro is some dynamic string content or html template that contains mustache
var macro = this.status == 'some_switch' ? '...{{payment.status}}...' : '...{{refund.status}}...';
Vue.component('cp-macro', {
data: function () {
return {
payment: vmCard1.payment,
refund: vmCard1.refund
}
},
template: '<span>'+macro+'</span>'
})
this.compiled = Vue.compile('<cp-macro></cp-macro>');
},
hide: function () {
this.compiled = null; // must remove for the next macro to show
}
}
})
</script>
I use this method in my project for rendering templates as reactive component. All I need is passing in props URL for download template or template for immediate render:
<div id="app"></div>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="https://unpkg.com/vue#3/dist/vue.global.js"></script>
<script>
const { createApp, defineComponent, markRaw } = Vue;
createApp({
template: `
<component v-if="component" :is="component"/>
<span v-else>Component is loading...</span>
`,
data: () => {
return {
component: undefined
}
},
provide: {
message: 'Hello Vue!'
},
mounted() {
setTimeout(async () => {
this.component = await this.defineRawComponent('<span>{{ message }}</span>')
}, 1000);
},
methods: {
async defineRawComponent(template, url) {
if (!template && !url) {
throw new Error('URL and template is not defined');
}
try {
let html = template;
if (!html) {
const { data } = await axios.get(url);
html = data;
}
return Promise.resolve(
markRaw(
defineComponent({
name: 'RawContent',
template: html,
inject: ['message']
})
)
);
} catch (err) {
return Promise.reject(err);
}
}
}
}).mount('#app')
</script>
I've written this code using mithril.js + CKEditor
<body>
<script>
var frm = {};
frm.vm = (function () {
var vm = {};
vm.afterLoad = function () {
CKEDITOR.replace( 'editor1' );
};
vm.btnClick = function () {
console.log(document.getElementById('editor1').value);
};
return vm;
})();
frm.controller = function () {
};
frm.view = function (controller) {
return m("div", {config: frm.vm.afterLoad}, [
m("textarea", {id: "editor1"}),
m("button", {onclick: frm.vm.btnClick}, "Click here to see the text you've typed")
])
;
};
m.mount(document.body, frm);
</script>
</body>
but when I click the button, I see this error:
Uncaught The editor instance "editor1" is already attached to the provided element.
and console.log() prints a blank line.
What am I doing wrong?
I found the problem. To get the value of the CKEditor, one needs to use
CKEditor.instance.nameoftextarea.getData()
This is driving my crazy, the first angular-slick is not working but the second is just fine, any idea what is going on?
I created a plunkr (in case someone is looking for an example in the future), but my problem is very odd because in my code/realproject is not working so I don't know what the hell is going on, anyway! here is the plunkr: http://plnkr.co/edit/URIbhoVpm1OcLSQqISPs?p=preview
I think the problem is related to the DOM because maybe angular needs to create the html before the carousel is render, I don't know... :(
This is the outcome:
https://db.tt/noc0VgGU
Router:
(function() {
'use strict';
angular
.module('mgxApp.landing')
.config(configFunction);
configFunction.$inject = ['$routeProvider'];
function configFunction($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'app/landing/landing.html',
controller: 'homeCtrl',
controllerAs: 'hC'
});
}
})();
Controller:
(function() {
'use strict';
angular
.module('mgxApp.landing')
.controller('homeCtrl', homeCtrl);
homeCtrl.$inject = ['modalFactory', 'channelFactory'];
function homeCtrl(modalFactory, channelFactory) {
var hC = this;
hC.openAuthModal = modalFactory.openAuthModal;
hC.activeChannels;
channelFactory.allActiveChannels().then(function(activechannels){
console.log(activechannels);
hC.activeChannels = activechannels;
});
hC.w = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
hC.breakpoints = [
{
breakpoint: 768,
settings: {
slidesToShow: 2,
slidesToScroll: 2
}
}, {
breakpoint: 480,
settings: {
slidesToShow: 1,
slidesToScroll: 1
}
}
];
}
})();
HTML VIEW:
// NOT WORKING
<slick class="slider single-item" responsive="hC.breakpoints" slides-to-show=3 slides-to-scroll=3>
<div ng-repeat="channel in hC.activeChannels">
{{channel.get("username")}}
</div>
</slick>
// Working fine
<slick class="slider single-item" current-index="index" responsive="hC.breakpoints" slides-to-show=3 slides-to-scroll=3>
<div ng-repeat="i in hC.w">
<h3>{{ i }}</h3>
</div>
</slick>
Factory and Promise:
(function () {
'use strict';
angular
.module('mgxApp.channel')
.factory('channelFactory', channelFactory);
channelFactory.$inject = ['$rootScope', '$q'];
function channelFactory($rootScope, $q) {
var service = {
allActiveChannels : allActiveChannels
};
return service;
function allActiveChannels() {
var deferral = $q.defer();
var User = Parse.Object.extend("_User");
var query = new Parse.Query(User).limit(10);
query.find({
success: function(users) {
console.log(users);
/*for (var i = 0; i < users.length; i++) {
console.log(users[i].get("username"));
}*/
deferral.resolve(users);
},
error: function(error) {
console.warn(error);
deferral.reject();
}
});
return deferral.promise;
}
}
})();
My working code
<div tmob-slick-slider sliderData="" dynamicDataChange="true" class="utilHeightImg marqueeContainer">
<slick id="productCarousel" class="slider" settings="vm.slickAccessoriesConfig" data-slick='{"autoplay ": true, "autoplaySpeed": 4000}'>
<!-- repeat='image' -->
<div ng-repeat="slideContent in vm.slides track by $index" >
<div bind-unsafe-html="slideContent" ></div>
</div>
<!-- end repeat -->
</slick>
</div>
you have to write a directive to reinitialize the slider
angular.module('tmobileApp')
.directive('tmobSlickSlider',['$compile',function ($compile) {
return {
restrict: 'EA',
scope: true,
link: function (scope, element, attrs) {
scope.$on('MarqueesliderDataChangeEvent', function (event, data) {
$compile(element.contents())(scope);
});
}
};
}]);
Write this in your controller
hc.selectView=false; // make this hc.selectView=true when your promise get resolve
$scope.$watch('hc.selectView', function(newValue, oldValue) {
$scope.$broadcast('MarqueesliderDataChangeEvent');
});
I ended up using this solution:
Angular-slick ng-repeat $http get
I'd suggest you to use ng-if on slick element. That will only load slick directive only when data is present just by checking length of data.
Markup
<slick ng-if="ctrl.products.length">
<div ng-repeat="product in ctrl.products">
<img ng-src="{{product.image}}" alt="{{product.title}}"/>
</div>
</slick>
I would like to send a post request to my API. It works with jQuery :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$.ajax({
type: "POST",
url: "api.php?option=inscription",
data: {lol : "mess"}
});
</script>
But it doesn't with AngularJS :
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> </script>
{{1+1}}
<script>
$http.post('api.php?option=inscription', {lol : "mess2"})
.success(function(){alert('cool');});
</script>
If someone can help me. Thank you !
UPDATE :
Thank for your answers, I wanted to simplify but it wasn't clear anymore. So with your help, this is my new code, and the problem is the same. The data in the backend is empty ;
frontend :
<html ng-app="myApp">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> </script>
<div ng-controller="MainCtrl"></div>
{{data}}
<script>
var app = angular.module('myApp', []);
app.service('SomeService', function($http) {
this.readData = function(dataUrl, dataTobePosted) {
var back = $http.post(dataUrl, dataTobePosted);
back.success(function(data){
console.log(data);
return data;
}).error(function(data, status, headers, config) {
return status;
});
}
});
app.controller('MainCtrl', function($scope, $http, SomeService){
$scope.readData = function(url) {
var dataTobePosted = {"lol": "mess"};
$scope.data = SomeService.readData(url, dataTobePosted);
}
$scope.readData('api.php?option=inscription');
});
</script>
</html>
For clarity, I am suggesting a simple implementation. However, further reading may needed in order to understand the behaviour precisely.
angular.module('myApp').service('SomeService', function($http) {
this.readData = function(dataUrl, dataTobePosted) {
// read data;
return $http.post(dataUrl, dataTobePosted)
.then(function(res) {
return res.data;
}, function(res) {
return res;
}
}
return this;
});
angular.module('myApp').controller('MyController', function($scope, SomeService) {
$scope.readData = function(url) {
var dataTobePosted = {"lol": "mess"};
SomeService.readData(url, dataTobePosted)
.then(function(res) {
$scope.data = res;
}, function(res) {
// Display error
}
}
$scope.readData('api.php?option=inscription');
}
Usage in the HTML page
<div ng-controller="MyController">
{{data}}
</div>
You're using AngularJS as if it's jQuery. It's not. AngularJS works with dependency injection, so you need to wrap your $http call inside a controller.
You should probably read up on AngularJS. A few useful links:
https://docs.angularjs.org/guide/introduction
https://docs.angularjs.org/guide/controller
https://docs.angularjs.org/guide/di
"Thinking in AngularJS" if I have a jQuery background?
My bad, my problem came from my backend in the php I just get my data with :
$data = json_decode(file_get_contents("php://input"));
and not with $_POST
Im using jQuery to delete and fade the item container. This code will delete and fade div class box2. what i want to do this to fade div class box1. without changing the delete link to box1.
if anyone can point me out how to do this, highly appropriated. thanks in advace.
<div class="box1">
<div class="box2">
x
</div>
</div>
JavaScript
<script type="text/javascript">
$(document).ready(function () {
$('#load').hide();
});
$(function () {
$(".delete").click(function () {
$('#load').fadeIn();
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id=' + id;
$.ajax({
type: "POST",
url: "delete.php",
data: string,
cache: false,
success: function () {
commentContainer.slideUp('slow', function () {
$(this).remove();
});
$('#load').fadeOut();
}
});
return false;
});
});
</script>
Try this code :
$(function() {
$('#load').hide();
$('.delete').click(function(){
$('#load').fadeIn();
$(this).parent().slideUp('slow', function () {
$('.delete').appendTo('.box1')
$(this).remove();
$('#load').fadeOut();
});
return false;
})
})
If you change it to var commentContainer = $(this).parent().parent();. It will now target .box1. You can then unwrap .box2 :
commentContainer.slideUp('slow', function() {
$('.box2').unwrap();
$(this).remove();
});
I believe you want
var commentContainer = $(this).parent().parent();
to get to .box1 and not .box2 Does that solve the problem?
Just a couple of comments though. A valid id should start with an alphabetic character. The digit '1' is not valid. 'a1' would be better, or just 'a'. Also use the ajax callback done rather than success as it is currently deprecated.