Code mirror not working with angular js binding variable - javascript

Html:
<body ng-app ng-controller="OrderFormController">
<!--<h1 class="errorHeader">List of Classes</h1>-->
<header>
<div class="container">
<div id="branding">
<h1>Apex <span class="highlight"> Editor </span> </h1>
</div>
</div>
</header>
<div class="col-md-12 col-lg-12">
<div class="panel with-nav-tabs panel-default">
<div class="panel-heading">
<ul class="nav nav-tabs">
<li class="active">Apex Editor</li>
</ul>
</div>
<div class="panel-body">
<div>
<input type="text" name="apexClass" id="autocomplete" placeholder="Type the name of the Apex class you want to edit"/>
</div>
<div class="btn-group-vertical" style="padding: 1%">
<button type="button" class="btn btn-primary" id="editBtn">Edit</button>
</button>
</div>
<div class="tab-content" align="left">
<div id='error' style='display:none'>{{apexClassWrapperError.message}}</div>
<div>{{apexClassWrapper.name}}</div>
<img src="../img/ajax-loader.gif" id="loaderImage" style='display:none'>
<form>
<textarea ng-model="apexClassWrapper.body" id="code" name="code" readonly="true" >{{apexClassWrapper.body}}</textarea>
</form>
</div>
<button type="button" class="btn btn-primary" id="saveBtn" ng-click="postdata(apexClassWrapper)">Save</button>
</div>
</div>
</div>
<script src="../js/makeEditable.js"></script>
<script>
$(function() {
var editor = CodeMirror.fromTextArea(document.getElementById("code"),{
linenumber : true,
matchBrackes: true,
mode: "text/x-apex"
})
});
</script>
<footer>
<p>Web based Apex Editor</p>
<p>Developed By - Nagendra Kumar Singh</p>
</footer>
</body>
CSS and JS files included at top:
<script src="../js/codemirror.js"></script>
<script src="../js/apex.js"></script>
<script src="../js/matchbrackets.js"></script>
<link href="../css/codemirror.css" rel="stylesheet"/>
The controller is a simple one fetching the class through a RESTApi.
function OrderFormController($scope, $http) {
$('#autocomplete').autocomplete({
type: 'POST',
serviceUrl: 'http://localhost:8989/getSuggestion',
onSelect: function (suggestion) {
console.log('suggestion.value -> '+suggestion.value);
var data = {
apexClassName:suggestion.value
};
var config = {
params: data
};
$('#loaderImage').show();
$http.get("http://localhost:8989/getApexBody",config).then(function (response) {
$scope.apexClassWrapper = response.data;
$('#loaderImage').hide();
});
}
});
};
But I can only see {{apexClassWrapper.body}} in my text area, I dont see the real code when using CodeMirror, If I remove code mirror , I can see the class, but I cannot figure out a way to show the body with CodeMirror included.
There are no errors in console log and all the JS and CSS files are loaded perfectly. Please help.

Ok, So I think I may have figured it out. What I did is I set a timeout for the codemirror code to run as follows in the js file and removed it from the index.html.
$('#loaderImage').show();
$http.get("http://localhost:8989/getApexBody", config).then(function (response) {
$scope.apexClassWrapper = response.data;
$('#loaderImage').hide();
if(globalEditor) {
globalEditor.toTextArea();
}
setTimeout(function (test) {
var editor = CodeMirror.fromTextArea(document.getElementById('apexBody'), {
lineNumbers: true,
matchBrackets: true,
mode: "text/x-apex"
});
globalEditor = $('.CodeMirror')[0].CodeMirror;
}), 2000
});
The only issue in this answer is that, it creates multiple code editor window when I try to load different classes. How can I resolve that?
So finally got it working, defined a global variable and using the method toTextArea

Related

Magnific Pop up wont close when you press Cancel on the Modal

I am using Magnific Pop up on a project, currently I have it on a ASP MVC project as a Modal:
Modal
div id="js_DeleteNewSongsPopup" class="theme-primary ajax-form popup-basic admin-form mfp-with-anim modalPopup">
<div class="panel">
<div class="panel-heading">
<span class="panel-title">
<i class="fa fa-ban "></i>Reject Selected Song
</span>
</div>
#* Information Body *#
<div class="panel-body p25">
<div class="section row">
<div class="col-md-12 text-center">
<h3>
Are you sure you want to <b class="text-danger">reject</b> the selected Songs?
</h3>
<p>
Please note, these will be <b class="text-danger">deleted</b> and no longer accessable
</p>
</div>
</div>
</div>
#* Form Body *#
<div class="panel-footer">
<div class="text-center">
<fieldset>
<input type="button" class="btn btn-primary js_CancelForm" value="Cancel" data-bind="click: function(){ $.magnificPopup.close(); }">
<input type="button" class="btn btn-danger js_DeleteNewSongsButton" value="Delete" data-bind="click: $root.submitDeleteNewSongs">
</fieldset>
</div>
</div>
</div>
<button title="Close (Esc)" type="button" class="mfp-close">×</button>
JavaScript
/* Delete New Songs Popup*/
$(document).on("click",
".js_DeleteNewSongs",
function (e) {
e.preventDefault();
var popup = $("#js_DeleteNewSongsPopup");
$.magnificPopup.open({
removalDelay: 500, //delay removal by X to allow out-animation,
items: {
src: $(popup)
},
callbacks: {
beforeOpen: function (e) {
this.st.mainClass = 'mfp-slideUp';
},
close: function () {
}
},
midClick: true
// allow opening popup on middle mouse click. Always set it to true if you don't provide alternative source.
});
return false;
});
Any ideas as there is no console errors being reported. I am also unsure why it is working on another page, when the mark-up is identical
Try:
$('body').removeClass('panel-body p25');
Or
$('body').removeClass('theme-primary ajax-form popup-basic admin-form mfp-with-anim modalPopup');
Basically you need to remove the "modal" class.
Ended up using:
$('.js_CancelForm').on("click", function () {
$.magnificPopup.close();
});
Now the Popup closes as expected.

How do I adjust marquee based on global variable? - Meteor

I'm developing an app using Meteor Framework.
One of the features I am looking to implement is having a marquee text (like a scrolling bottom text).
I have added the package meteor-jquery-marquee and it works great with a single string. But whenever I try to modify the string, nothing happens, and it stays the same.
It's worth mentioning that I did try sessions, and it changes the text, however, the marquee animation stops, which defeats the purpose.
I have been stuck for hours trying to get it to work, some help would really save my butt here.
I've initialized the global variable in the client/main.js as
globalMessage = "Welcome to my proJECT";
And it scrolls with the marquee just fine.
Thank you in advance!
My code:
My body template
<template name="App_Body">
{{> Header}}
{{>Template.dynamic template=main}}
{{> Footer}}
<div style="color: white;" class="ui center aligned container">
<div class='marquee'>{{globalMessage}}</div>
</div>
</template>
body.js
Template.App_Body.helpers({
globalMessage () {
return globalMessage;
},
});
where I'm trying to edit the marquee:
<template name="dailyMessageControl">
<div class="container">
<br>
<br>
<div class="info pull-right"> <!-- column div -->
<div class="panel panel-default">
<div class="panel-heading clearfix">
<h1 class="panel-title text-center panel-relative"> Modify Daily Message</h1>
</div>
<div class="list-group">
<div class="list-group-item">
<p style="font-size: 30px;">Current Message: <br>{{globalMessage}}</p>
</div>
<div class="panel-footer">
<form>
<div class="form-group">
<label for="exampleInputEmail1">Enter new messages</label>
<input type="text" name="newMsg" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="New Message">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
</div><!-- end column div -->
</div>
</template>
the .js
Template.dailyMessageControl.helpers({
globalMessage () {
return globalMessage;
},
});
Template.dailyMessageControl.events({
'submit form': function(){
event.preventDefault();
var newMsg = event.target.newMsg.value;
globalMessage = newMsg;
}
});
Your code clearly lacks reactivity, let's fix that.
Fist, initialize globalMessage as ReactiveVar instance (client/main.js):
globalMessage = new ReactiveVar('Welcome to my proJECT');
Next, code to react to its value change (body.js):
Remove globalMessage() helper
Add code that will track globalMessage variable and re-create $.marquee:
Template.App_Body.onRendered(function appBodyOnRendered() {
this.autorun(() => {
const value = globalMessage.get();
const $marquee = this.$('.marquee');
$marquee.marquee('destroy');
$marquee.html(value);
$marquee.marquee(); // add your marquee init options here
});
});
And, lastly, update code in dailyMessageControl template to work with ReactiveVar instance:
Template.dailyMessageControl.helpers({
globalMessage () {
return globalMessage.get(); // changed line
},
});
Template.dailyMessageControl.events({
'submit form': function(){
event.preventDefault();
var newMsg = event.target.newMsg.value;
globalMessage.set(newMsg); // changed line
}
});

Javascript issue in Laravel 5

I'm learning laravel 5 about one month, and now i having a problem with javascript.
I add an form click on blade file to delete the post.
But now i don't want to use form, i replace that by javascript.
How can i detect when use touch the delete'button.
#extends ('layouts.master')
#section ('head.title')
Blog
#stop
#section ('body.content')
<div class="container">
<div class="row">
<div class="col-sm-6 col-sm-offset-3">
</div>
</div>
<form class="form-show">
<div class="row">
<div class="col-sm-6 col-sm-offset-3">
<h2> {{ $article->title}} </h2>
<p> {{ $article->content}} </p>
</div>
<div class="row">
<div class="col-sm-6 col-sm-offset-3">
Cập nhật
<button type="submit" class="btn btn-primary">Xoa</button>
</div>
</div>
</div>
</form>
</div>
<script src="jshow.js"></script>
#stop
Add id to button so it is easily locatable in Javascript
<button id="delete-button" type="submit" class="btn btn-primary">Xoa</button>
Next add this javascript
var deleteButton = document.getElementById("delete-button");
deleteButton.onclick = function() { delete(); return false; }
Process the deleting in delete() method
Try this :
<!DOCTYPE html>
<html>
<body>
<button onclick="myFun()">Click me</button>
<p id="demo"></p>
<script>
function myFun() {
console.log('Clicked');
}
</script>
Since HTML forms can't make PUT, PATCH, or DELETE requests, you will need to add a hidden _method field to spoof these HTTP verbs
Also, don't forget to add csrf-token as well which is needed in order to validate a POST request.
First add this meta tag inside your <head>.
<meta name="csrf-token" content="{{ csrf_token() }}">
Then place this code at the top of your JS file.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Now, you can make use of data-* attribute to hold the route of that article for AJAX.
<button data-route="{{ route('article.destroy', $article->id) }}" class="btn btn-danger deleteArticle">Delete</button>
In your JS
document.querySelector('.deleteArticle').addEventListener('click', function() {
var route = this.dataset.route;
if (confirm("Are you sure you wish to delete this article?")) {
$.ajax({
method: 'POST',
url: route,
data: {
"_method": 'DELETE',
},
success: function() {
// handle success here
},
error: function() {
// handle error here
},
});
}
});

AngularJS view not updating

I'm trying to make my first AngularJS application and I've run into a problem.
I have an input:
<input ng-model="userNameLogin" type="text" placeholder="username" class="form-control">
A button:
<button ng-click="setActiveUser()" type="submit" class="btn btn-success">Sign in</button>
and an expression:
{{ activeUser }}
I want the text to change to whatever was typed in the input once the button is clicked. For that I have the following controller:
app.controller('View1Ctrl', ['$scope', function($scope) {
$scope.userNameLogin = "";
$scope.activeUser = "Test";
$scope.setActiveUser = function() {
$scope.activeUser = $scope.userNameLogin;
console.log($scope.activeUser);
};
}]);
The initial value "Test" is shown just fine and according to the console the value of "activeUser" is being changed correctly as well. But the text in the view stays the same.
I have seen similar questions where a $scope.$apply() was the answer, but if I add that after the console.log I get
"Error: [$rootScope:inprog] $apply already in progress".
What am I missing here?
EDIT:
I have noticed that If I put the input, button and expression in the same HTML file it all works fine. However my Input and button are in a navbar in index.html while the expression is in view1.html
This is the body of index.html:
<body ng-app="myApp.view1">
<nav class="navbar navbar-inverse navbar-fixed-top" ng-controller="View1Ctrl as view">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="#/view1">Kwetter</a>
</div>
<div class="navbar-collapse collapse" >
<ul class="nav navbar-nav">
<li>Home</li>
<li>Profile</li>
</ul>
<form class="navbar-form navbar-right">
<div class="form-group">
<input ng-model="userNameLogin" type="text" placeholder="username" class="form-control">
</div>
<div class="form-group">
<input type="password" placeholder="password" class="form-control">
</div>
<button ng-click="setActiveUser()" type="submit" class="btn btn-success">Sign in</button>
</form>
</div>
</div>
</nav>
<div id="pagewrapper" class="container">
<div ng-view></div>
<div>Angular seed app: v<span app-version></span></div>
</div>
and this is my view1.html
<div ng-controller="View1Ctrl as view">
<!-- row 1: welcome -->
<div class="row">
<div class="col-md-12 pull-left">
<image ng-src="{{ view.users[0].avatar }}"/>
<!-- If I put the button and input here it will work -->
<input ng-model="userNameLogin" type="text" placeholder="username" class="form-control">
<button ng-click="setActiveUser()" type="submit" class="btn btn-success">Sign in</button>
{{ activeUser }}
</div>
</div>
<!-- row 2: main content -->
<!-- left the rest of the content out because it would just clutter the page -->
I tried placing the ng-controller in <div id="pagewrapper" class="container"> instead of the first div of view1.html, but that made no difference.
I think u have misplaced the button or textbox or expression,
note : these should be inside the ng-controller.
please try this, it will work
<html>
<head>
<script data-require="angular.js#*" data-semver="1.4.0-beta.6" src="https://code.angularjs.org/1.4.0-beta.6/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="app">
<div ng-controller="View1Ctrl">
<input ng-model="userNameLogin" type="text" placeholder="username" class="form-control">
<button ng-click="setActiveUser()" type="submit" class="btn btn-success">Sign in</button>
{{activeUser}}
</div>
<h1>Hello Plunker!</h1>
</body>
</html>
script.js code
var app = angular.module("app",[]);
app.controller('View1Ctrl', ['$scope', function($scope) {
$scope.userNameLogin = "";
$scope.activeUser = "Test";
$scope.setActiveUser = function() {
$scope.activeUser = $scope.userNameLogin;
console.log($scope.activeUser);
};
}]);
refer http://plnkr.co/edit/ixbByBQ9nGm4XEqEFi4t?p=preview
You have the properties directly on $scope and that is breaking the binding. Instead try:
app.controller('View1Ctrl', ['$scope', function($scope) {
$scope.userInfo = {
userNameLogin: "",
activeUser:"Test"
}
$scope.setActiveUser = function() {
$scope.uesrInfo.activeUser = $scope.userInfo.userNameLogin;
console.log($scope.activeUser);
};
}]);
and in your view:
{{userInfo.activeUser}}
From Egghead.io https://egghead.io/lessons/angularjs-the-dot
Within your code I can't see anything causing the problem. I made a fiddle, that shows that your code works:
http://jsfiddle.net/xxvsn8xs/
You need to declare the ng-appand the ng-controller of course, like in the fiddle, to let the app work at all.
Also, an view update might not occur, if setting the activeUser actually occurs outside of the angular scope, which might be within an external library or whatever. It is true, that these could be achieved by calling $scope.$apply() directly, but it is nor recommended, as the digest might already be in progress. This is the case in your code, as why you get the according error message.
Instead use angulars $timeout service with a callback and 0 delay, that applies the value to $scope.activeUser. $timeout will check, if a digest cycle is in progress and if not, will start one.
$scope.setActiveUser = function() {
$timeout(function () {
$scope.activeUser = $scope.userNameLogin;
console.log($scope.activeUser);
});
};
Don't forget to define $timeout in your controllers dependencies:
app.controller('View1Ctrl', ['$scope', '$timeout', function($scope, $timeout) {
Angular watches the variable you bind to $scope, but if you replace that variable Angular is not able to detect it. That's why $apply would be a suggestion.
Another suggestion is to bind the variable to a 'model' variable:
app.controller('View1Ctrl', ['$scope', function($scope) {
$scope.userNameLogin = "";
$scope.myData = { activeUser: "Test" };
$scope.setActiveUser = function() {
// Angular will pick up the change in the myData object, and will update all variables attached to it
$scope.myData.activeUser = $scope.userNameLogin;
console.log($scope.myData.activeUser);
};
}]);
view:
{{ myData.activeUser }}
Do you execute your application in Apache ? I'd the same issue when I was using file:// And I fixed my issue by using a localhost.
I put my navbar (containing the input and button) in a partial and made a new directive for it. Instead of placing the navbar in the index.html I put it in the individual partials and now it works fine. I suspect the problem had something to do with different scopes.
navbar html:
<a class="navbar-brand" href="#/view1">
Kwetter
<image id="navbar-image" src="src/kwetter_logo.png"/>
</a>
</div>
<div class="navbar-collapse collapse" >
<ul class="nav navbar-nav">
<li>Home</li>
<li>Profile</li>
</ul>
<form class="navbar-form navbar-right">
<div class="form-group">
<input ng-model="userNameLogin" type="text" placeholder="username" class="form-control">
</div>
<div class="form-group">
<input type="password" placeholder="password" class="form-control">
</div>
<button ng-click="setActiveUser()" type="submit" class="btn btn-success">Sign in</button>
</form>
</div>
</div>
the directive:
app.directive('navbar', function() {
return {
restrict: 'E',
templateUrl: 'partials/navbar.html',
controller: 'View1Ctrl as view'
}
});
Then I just added <navbar></navbar> to every view where I want a navbar.
Thanks everyone, your help pushed me in the right direction.

AngularJS, only runs correctly in firefox why?

I'm using angularjs. The example I have done works perfectly in firefox, but does not work any other browser.
The error that appears in other browsers when I press add picture botton in index is:
XMLHttpRequest cannot load file:///C:/...../gifwallet/add_gif.html. Cross origin requests are only supported for HTTP.
I do not understand is what is wrong.
index.html
<html lang="es" ng-app="gifwalletApp">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<link rel="stylesheet" href="stylesheets/app.css">
<script src="javascripts/angular.js"></script>
<script src="javascripts/angular-translate.js"></script>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script src="src/app.js"></script>
<script src="javascripts/ui-bootstrap-tpls-0.11.0.min.js"></script>
<title>GIF Wallet</title>
</head>
<body>
<div class="container">
<div ng-controller="TranslateController">
<button ng-click="changeLanguage('es')" translate="BUTTON_TEXT_ES"></button>
<button ng-click="changeLanguage('en')" translate="BUTTON_TEXT_EN"></button>
</div>
<header ng-controller="MenuController">
<ul class="nav nav-pills pull-right">
<li class="active">
<a href="#">
<span class="glyphicon glyphicon-home"></span>
<span class="badge pull-right">42</span>
</a>
</li>
<li>
<span class="glyphicon glyphicon-plus"></span>
</li>
<li>
<span class="glyphicon glyphicon-search"></span>
</li>
</ul>
<h3 class="text-muted">GIF Wallet</h3>
</header>
<div id="images" class="row" ng-controller="gifListController">
<div class="col-lg-12 media" ng-repeat="gif in giflist">
<a href="" class="pull-left thumbnail">
<img class="media-object" src="{{ gif.url }}">
</a>
<div class="media-object">
<h4 class="media-heading">{{ gif.name }}</h4>
<p>
<a><span class="glyphicon glyphicon-minus"></span> {{ 'FAVORITO' | translate }}</a>
</p>
<p>
<a><span class="glyphicon glyphicon-heart"></span> {{ 'ELIMINAR' | translate }}</a>
</p>
<p>
Link: {{ gif.url }}
</p>
</div>
</div>
</div>
<footer>
<p>© GIFWallet 2014</p>
</footer>
</div>
app.js
var gifwalletApp = angular.module('gifwalletApp', ['ui.bootstrap','pascalprecht.translate']);
gifwalletApp.config(function($translateProvider) {
$translateProvider.translations('en', {
FAVORITO: 'Favorite',
ELIMINAR: 'Delete'
})
.translations('es', {
FAVORITO: 'Favorito',
ELIMINAR: 'Eliminar'
});
$translateProvider.determinePreferredLanguage();
});
gifwalletApp.controller('TranslateController', function($translate, $scope) {
$scope.changeLanguage = function (langKey) {
$translate.use(langKey);
};
});
gifwalletApp.controller('gifListController', ['$rootScope','$scope','Storage','$http',
function($rootScope,$scope,Storage,$http){
$scope.giflist = Storage.list();
$rootScope.$on('reloadList', function(event, data){
$scope.giflist = Storage.list();
});
}]);
gifwalletApp.controller('MenuController', ['$rootScope','$scope', 'Storage','$modal',
function($rootScope,$scope, Storage, $modal) {
$scope.add = function() {
$modal.open({
templateUrl: 'add_gif.html',
controller: function($scope, $modalInstance) {
$scope.Gif = {};
$scope.save = function() {
var image = {
'name': $scope.Gif.name,
'url': $scope.Gif.url,
'tags': [],
'favorite': false
};
Storage.save(image);
$rootScope.$broadcast('reloadList');
$modalInstance.dismiss('cancel');
};
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
}
});
};
}
]);
gifwalletApp.service('Storage', ['$window', function($window) {
var images = [];
if (!$window.localStorage) {
alert('No tienes localStorage activado');
} else {
images = $window.localStorage.getItem('gifWallet');
}
this.save = function(image) {
if (images == null) {
images = [];
}
else {
images = angular.fromJson(images);
}
images.push(image);
imagesString = JSON.stringify(images);
$window.localStorage.setItem('gifWallet', imagesString);
}
this.get = function(key) {
}
this.remove = function(key) {
}
this.list = function() {
return angular.fromJson($window.localStorage.getItem('gifWallet'));
}
}]);
add_gif.html
<div class="modal-header">
<h3 class="modal-title">Agregar GIF</h3>
<p class="text-muted">Añade un gif favorito a tu wallet usando el nombre y la URL</p>
</div>
<div class="modal-body">
<form action="" role="form">
<div class="form-group">
<label for="name">Nombre</label>
<input type="text" id="name" ng-model="Gif.name" placeholder="Corgi bailarín" class="form-control">
</div>
<div class="form-group">
<label for="url">URL</label>
<input type="url" id="url" ng-model="Gif.url" placeholder="http://..." class="form-control">
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-link" ng-click="cancel()">Cancelar</button>
<button class="btn btn-primary" ng-click="save()">Agregar GIF</button>
</div>
You shouldn't be using the src attribute with Angular Expressions.
Use ngSrc - as described in the docs.
<img class="media-object" ng-src="{{ gif.url }}">
Edit:
In your modalpanel you'll need to make sure the form that is beeing submitted is valid
Moved here from comment:
The reason why it won't work without the http:// is probably because the input field for the URL is of type="url" and urls are not valid with http/https. So it actually is a different problem here. The form should be validated before adding an image. :)
When you call partials in Angular, it makes a cross domain request. Firefox allows it, Chrome and others don't.
So, you have to launch a local web server to make it run on all browsers (Apache, with Xampp / Mamp, whatever).
Your script only runs on firefox because firefox allow cross origin requests (AJAX requests)
and chrome will not allow cross origin request because of security policies.
So in order to run your script in chrome You have to disable web security in chrome
To disable web-securities in chrome:
kill the chrome process
press "ctrl+R" to open run menu
type "chrome --disable-web-security" without quotes and press enter
then you will be able to run your script
Please let me know If you have any issues with other browsers?

Categories

Resources