When I press my button, I want to print the value of my textbox in my console. But my textbox returns a undefined. It seems that all of the code are working perfect, I did it the same way as some other code I used before, but it isn't working now.
This is my html code:
<form class="form-horizontal">
<input type="text" ng-model="add" ng-model-instant><button class="btn" ng-click="order()"><i class="icon-plus"></i>Order!</button>
</form>
This is my script:
angular.module('MyApp', []).
config(function($routeProvider) {
$routeProvider.
when('/boeken', {templateUrl:'partials/boeken.html', controller:BoekenCtrl}).
when('/orders', {templateUrl:'partials/orders.html', controller:OrderCtrl}).
when('/home', {templateUrl:'partials/home.html', controller:HomeCtrl}).
otherwise({redirectTo:'/home'});
});
//BoekenCtrl
//HomeCtrl
function OrderCtrl($rootScope) {
$rootScope.order = function() { console.log($rootScope.add); $rootScope.add = ""; };
}
Why is it that my textbox is undefined?
Instead
function OrderCtrl($rootScope) {
$rootScope.order = function() { console.log($rootScope.add); $rootScope.add = ""; };
}
use:
function OrderCtrl($scope) {
$scope.order = function() {
console.log($scope.add);
$scope.add = "";
};
}
Since your form exists under OrderCtrl, you need to use $scope into OrderCtrl controller to fetch any data. But, sure, you can store it after in $rootScope
Please, see the example in Fiddle
Related
I am trying to use a service to set title in controller1 and then access title in controller2.
sharedProperties.setTitle(title) works in controller1, but when I try to get the title in controller2, it gets "title" (the initial value) instead of the new value.
I've also tried storing title in an object but it didn't work.
app.service('sharedProperties', function () {
var title = "title"
return {
getTitle: function () {
return title;
},
setTitle: function (val) {
title = val;
}
}
});
app.controller('controller1', ['$scope', 'sharedProperties', function ($scope, sharedProperties) {
$('body').on("click", "button[name=btnListItem]", function () {
// gets the title
var title = $(this).text();
// sets the title for storage in a service
sharedProperties.setTitle(title);
});
}]);
app.controller('controller2', ['$scope', 'sharedProperties', function ($scope, sharedProperties) {
$scope.sharedTitle = function() {
return sharedProperties.getTitle();
};
}]);
And in my view, I have {{ sharedTitle() }} which should, as I understand it, update the title text with the new title.
Also, in case this is relevant: the two controllers are linked to two different html pages.
What am I doing wrong?
EDIT
Updated button listener:
$('body').on("click", "button[name=btnListItem]", function () {
// gets the text of the button (title)
var title = $(this).text();
sharedTitle(title);
alert(sharedProperties.getTitle());
document.location.href = '/nextscreen.html';
});
$scope.sharedTitle = function (title) {
sharedProperties.setTitle(title);
};
It seems to be correct in your sample code. I setup jsfiddle and it seems work correctly. Finding out a difference between my jsfiddle and your actual code would help you to find the problem you should solve.
Javascript:
angular.module('testapp', [])
.service('sharedProperties', function(){
var title = 'title';
return {
getTitle: function(){
return title;
},
setTitle: function(val){
title = val;
}
};
})
.controller('controller1', function($scope, sharedProperties){
$scope.change_title = function(newvalue){
sharedProperties.setTitle(newvalue);
};
})
.controller('controller2', function($scope, sharedProperties){
$scope.sharedTitle = function(){
return sharedProperties.getTitle();
};
})
Html:
<div ng-app="testapp">
<div ng-controller="controller1">
<input ng-model="newvalue">
<button ng-click="change_title(newvalue)">Change Title</button>
</div>
<div ng-controller="controller2">
<span>{{sharedTitle()}}</span>
</div>
</div>
My jsfiddle is here.
You have to print console.log(sharedProperties.getTitle()); Dont need return from controller.
So your code of controller2 is $scope.sharedTitle = sharedProperties.getTitle();
You need to use the $apply so that angular can process changes made outside of the angular context (in this case changes made by jQuery).
$('body').on("click", "button[name=btnListItem]", function () {
// gets the title
var title = $(this).text();
// sets the title for storage in a service
$scope.$apply(function() {
sharedProperties.setTitle(title);
});
});
See plunker
That said, this is BAD PRACTICE because you're going against what angular is meant for. Check “Thinking in AngularJS” if I have a jQuery background?. There are cases when you need to use $apply like when integrating third party plugins but this is not one of those cases.
I have the following form:
#Html.BeginForm("ActionMethod","Controller",FormMethod.Post)
On submission I want to run a Javascript function, so I added the following:
#Html.BeginForm("ActionMethod","Controller",FormMethod.Post, new { onsubmit = "myJsFunction()" })
But, it doesn't work... What am I doing wrong? Thanks!
You need this instead:
#using (Html.BeginForm("ActionMethod","Controller",FormMethod.Post, new { onsubmit = "return myJsFunction()" }))
{
//form
}
Notice the using this makes the form self closing, without the using you need to close it as detailed in this MSDN article.
You can confirm javascript is called with this to isolate the problem:
#using (Html.BeginForm("ActionMethod","Controller",FormMethod.Post, new { onsubmit = "alert('test')" }))
{
<input type="submit" value="test" />
}
This should pop up an alert.
If the first one fails and the second one works, there is a problem with your js script references. This would raise an error in your browser console.
Update
Instead of binding your form obtrusively, if you give your form an Id you could use the following jquery instead (jQuery reference):
#using (Html.BeginForm("ActionMethod","Controller",FormMethod.Post, new { id = "target"}))
{
//form
}
<script>
$(function () {
$("#target").submit(function (event) {
event.preventDefault();
myJsFunction();
});
});
</script>
This would bind when the form when the document is ready.
#using (Html.BeginForm("Edit", "Home", FormMethod.Post, new { id = "form1Demo", onsubmit = "return CheckSubmit(event);" })){
//form
}
<script>
function CheckSubmit(e) {
var Name = $("#Name").val();
var Roll = $("#Roll").val();
var Price = $("#Price").val();
if (Name == "" || Roll == "" || Price == "") {
$("#msg").html("Please Enter All Values!");
swal("Validation Error!", "Please Insert All Values", "warning");
return false;
}
return true;
}
</script>
I hope I am clear enough with this request for assistance, as it is hard to explain and I can't post all the code here. I have downloaded code to enable TinyMCE to be used in a NgRepeat with AngularJS:
angular.module('ui.tinymce', [])
.value('uiTinymceConfig', {})
.directive('uiTinymce', ['uiTinymceConfig', function (uiTinymceConfig) {
uiTinymceConfig = uiTinymceConfig || {};
var generatedIds = 0;
return {
require: 'ngModel',
link: function (scope, elm, attrs, ngModel) {
var expression, options, tinyInstance;
// generate an ID if not present
if (!attrs.id) {
attrs.$set('id', 'uiTinymce' + generatedIds++);
}
options = {
// Update model when calling setContent (such as from the source editor popup)
setup: function (ed) {
ed.on('init', function (args) {
ngModel.$render();
});
// Update model on button click
ed.on('ExecCommand', function (e) {
ed.save();
ngModel.$setViewValue(elm.val());
if (!scope.$$phase) {
scope.$apply();
}
});
// Update model on keypress
ed.on('KeyUp', function (e) {
ed.save();
ngModel.$setViewValue(elm.val());
if (!scope.$$phase) {
scope.$apply();
}
});
},
mode: 'exact',
elements: attrs.id
};
if (attrs.uiTinymce) {
expression = scope.$eval(attrs.uiTinymce);
} else {
expression = {};
}
angular.extend(options, uiTinymceConfig, expression);
setTimeout(function () {
tinymce.init(options);
});
ngModel.$render = function () {
if (!tinyInstance) {
tinyInstance = tinymce.get(attrs.id);
}
if (tinyInstance) {
tinyInstance.setContent(ngModel.$viewValue || '');
}
};
}
};
}]);
var gwApp = angular.module('gwApp', ['ui.tinymce']);
I don't really understand this code, but it works fine initially. My page starts with a list of Posts. I click on 'Show Reply' for the first post, and using NgSwitch the multiple replies become visible (nested NgRepeat). I submit a new reply message (the reply text is entered using tinymce) using a RESTful API service and a http call (too much code to post here). Then after clicking the submit button for the new reply message, the NgSwitch kicks in again unexpectedly to make the replies no longer visible. When I expand the replies again, the tinymce is just a regular textarea again, and the proper editor is gone.
I know this is not very clear, but I'm hoping someone can make sense of what I've written and can help me solve this problem..
I was having the same problem using ng-switch and ng-show so i added:
scope.$watch('onHidden()',function(){ tinymce.editors = [] });
after the setTimeout function.
Also replace the
ed.on('init',function(args){ ngModel.$render(); });
with
ed.on('init',function(args){ ed.setContent(ngModel.$viewValue); });
and remove the $render function.
This is the link to the working code in JsFiddle
I need to clear a textbox and a select-list after a button is clicked.This is what I tried but it doesn't seems to work:
HTML:
<input type="text" ng-model="Model.CurrentDowntimeEvent.Comment" size="60" placeholder="ENTER IN ANY ADDITIONAL INFORMATION"/><br>
<select class="categories" ng-disabled="selectlistdisabled" ng-model="Model.CurrentDowntimeEvent.CategoryId" ng-options="downtimeCategory.CategoryId as downtimeCategory.CategoryName for downtimeCategory in Model.DowntimeCategories">
</select>
<button ng-click="StopCurrentDowntime()">Stop Downtime Event</button>
JS:
angular.module('myApp', [])
.controller('DowntimeController', function ($scope, $http) {
$scope.Model = new Model($http);
$scope.StopCurrentDowntime = function () {
$scope.CurrentDowntimeEvent.Comment = '';
$scope.CurrentDowntimeEvent.CategoryId = '';
}
});
Instead of using button to clear input fields you can use reset (input type="reset") inside the form
You are missing Model. in your JS
angular.module('myApp', []).controller('DowntimeController', function ($scope, $http) {
$scope.Model = new Model($http);
$scope.StopCurrentDowntime = function () {
$scope.Model.CurrentDowntimeEvent.Comment = '';
$scope.Model.CurrentDowntimeEvent.CategoryId = '';
}
});
I'm using Malsup's excellent Form plugin to dynamically load search results onto the same page.
It works great with a standard form submit, however I have 2 select elements in my form and would love for the results to update as the select is changed.
My code at the moment is thus:
$(document).ready(function() {
var options = {
target: '#bands-results',
beforeSubmit: showRequest
};
$('#bandsearch').ajaxForm(options);
});
// Show loading message and submit form
function showRequest(formData, jqForm, options) {
$('#bands-results').prepend('<span>Searching</span>');
return true;
}
I haven't seen other examples that do the same.
Help appreciated.
Got it licked with this
$(document).ready(function() {
$("#genre-filter").change(function() {
$("#band_search").submit();
});
// bind to the form's submit event
$('#band_search').ajaxForm({
beforeSubmit: showRequest,
target: '#band_list',
success: function() {
$('#premlim').hide();
}
});
})
function showRequest(formData, jqForm, options) {
return true;
}