What is the Razor syntax for adding a C# condition in the script tag - razor

I have a script tag in my Razor cshtml file. I would like to conditionally add Javascript based on a property in my model.
Here is what I have done. Both attempts work. But is there a better way, e.g. what if my Javascript is more than a single line of code?
Attempt 1
#section scripts{
<script>
$(document).ready(function() {
#if (Model.IsAdding)
{
#Html.Raw("window.scrollTo(0, document.body.scrollHeight);")
;
}
</script>
}
Attempt 2
#section scripts{
<script>
$(document).ready(function() {
#(Model.IsAdding? "window.scrollTo(0, document.body.scrollHeight);" : "")
});
</script>
}

You can use the <text></text> tag
#section scripts {
<script>
$(document).ready(function () {
#if (Model.IsAdding)
{
<text>
// add your javascript code here
alert("test");
</text>
}
}
</script>
}

Related

How to access $(this) div in angularjs

I want to change the background of div that is clicked. So, how i can access $(this) div in angular?
My code is:
<div id="single" ng-click="changeit()">
foobar
</div>
And function is:
$scope.changeit=function($scope){
// jquery code $(this).css({"background":"#A4A4A4"});
// how in angular ?
}
You can pass the $event and use target to retrieve the current clicked element.
<div id="single" ng-click="changeit($event)">
asad
</div>
$scope.changeit = function ($event) {
$($event.target).css({ 'background': '#A4A4A4' });
}
Using a directive way, you could do it like this :
<div id="single" data-change-color>foobar</div>
And the changeColor directive which adds a click event on the element and changes the color when clicking on it.
(function () {
'use strict';
angular
.module('myModuleName')
.directive('changeColor', changeColor);
changeColor.$inject = [];
function changeColor () {
return {
restrict: 'A',
scope: {},
link: link
};
function link (scope, element) {
element.on('click', onClick(element));
}
function onClick (element) {
return function () {
element.css({ 'background': '#A4A4A4' });
}
}
}
}) ();
DOM manipulation should ideally be the sole domain of directives when using angular. This keeps us from gluing our controller logic into our DOM presentation which makes for a horrible mess. With this in mind Angular has two directives related to styling, ng-style and ng-class. Ng-class is demonstrated below.
https://docs.angularjs.org/api/ng/directive/ngStyle
https://docs.angularjs.org/api/ng/directive/ngClass
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js#1.4.3" data-semver="1.4.3" src="https://code.angularjs.org/1.4.3/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
<style>
.active{
background:red;
}
</style>
</head>
<body ng-controller="ctrl">
<button ng-click="activeButton = 1" ng-class="{'active' :activeButton==1}">Button 1</button>
<button ng-click="activeButton =2" ng-class="{'active' :activeButton==2}">Button 2</button>
<button ng-click="activeButton = 3" ng-class="{'active' :activeButton==3}">Button 3</button>
<script>
var app = angular.module("app",[]);
app.controller("ctrl",function(){});
angular.bootstrap(document,[app.name]);
</script>
</body>
</html>

Angular does not update UI for keyboard event

I want to update page for keyboard event.
I wired the keyboard event through $window.document.onkeydown. (I know this is not good but it is supposed to work)
However, I find that the page is not updating even the model is changed!
Where am I missing ?
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script>
function Main ($scope, $window) {
$scope.keyCode = 0;
$window.document.onkeydown = function (event) {
$scope.keyCode = event.keyCode;
console.log($scope.keyCode); //the model is changed here
};
}
</script>
</head>
<body ng-app>
<div ng-controller="Main">
{{keyCode}}
</div>
<script type="text/javascript" src="bower_components/angular/angular.js"></script>
</body>
</html>
---Edit---
Here is the code snippet you can try
http://plnkr.co/edit/DFUfHzQPla031IEDdCo3?p=preview
Whenever you want to execute an expression that is outside Angular's scope you need to let Angular know that a change has been made so it can perform a proper digest cycle. You can do this using the $scope.$apply() method. So your example becomes:
function Main ($scope, $window) {
$scope.keyCode = 0;
$window.document.onkeydown = function (event) {
$scope.$apply(function () {
$scope.keyCode = event.keyCode;
console.log($scope.keyCode);
});
};
}
Please see updated plunker here

Angular - append html through different frames with one module per frame

My code have the main windonw and one iframe and each one with your module. A button in main window fires click event that should append html into iframe, the new html when appended into that should apply interceptors and directives properly, but it doesn't work!
Angular javascript:
angular.module('module1',[]).controller('Controller1', function ($scope) {
$scope.get = function(){
$http.jsonp("some_url_here").success(function(html){
$scope.content = html;
});
}
}).directive('click', function($compile) {
return {
link: function link(scope, element, attrs) {
element.bind('click',function(){
var unbind = scope.$watch(scope.content, function() {
var div=document.getElementById("frame").contentWindow.angular.element("divId");
div.append($compile(scope.content)(div.scope()));
unbind();
});
});
}
}
});
angular.module('module2',[]).directive('a', function() {
return {
restrict:'E',
link: function(scope, element, attrs) {
console.log('ping!');
console.log(attrs.href);
}
};
});
Html code:
<html ng-app="modile1">
<div ng-controller="Controller1">
<button type="button", ng-click="get('any_value')", click:""/> Load frame
</div>
<iframe id="frame" src="/please/ignore/this">
<!-- considere the html as appended from iframe-src and contains ng-app="module2" -->
<html ng-app="module2">
<div id="divId">
<!-- code should be inject here -->
</div>
</html>
</iframe>
</html>
Please, considere that angularjs, jquery if applicable, modules-declaration as well as headers are loaded properly.
I'd like to load the html content from main-frame/window into iframe and run interceptors and directives properly. Is it possible? If yes, how can I do it?
Thanks for advancing!
I've tried this code and it seems work fine! I found it here: http://www.snip2code.com/Snippet/50430/Angular-Bootstrap
var $rootElement = angular.element(document.getElementById("frame").contentWindow.document);
var modules = [
'ng',
'module2',
function($provide) {
$provide.value('$rootElement', $rootElement)
}
];
var $injector = angular.injector(modules);
var $compile = $injector.get('$compile');
$rootElement.find("div#divId").append(scope.content);
var compositeLinkFn = $compile($rootElement);
var $rootScope = $injector.get('$rootScope');
compositeLinkFn($rootScope);
$rootScope.$apply();

jQuery click function and list items

Lately, I'm having trouble with jQuery click events. In this example, I'm wanting to use ajax post when an user clicks on a list item. No errors pop up on Firebug and the jquery script is in the code. When I run the code, nothing happens. The code is below.
<script type="text/javascript" >
$('#pop').click(function() {
var pop = 'pop';
$.post('ajax_file.php', {
style: pop
}, function(data) {
$('#tube').html(data);
});});
</script>
<ul>
<li id="pop">Pop</li>
</ul>
Try this:
$(document).ready(function(){
$('#pop').click(function() {
var pop = 'pop';
$.post('ajax_style_homepage.php', {
style: pop
}, function(data) {
$('#tube').html(data);
});
});
})
Wrap it in the document ready function and see what happens. Also you dont need to empty. You can call the html method and it will overwrite the content.
$(function(){
$('#pop').click(function() {
var pop = 'pop';
$.post('ajax_style_homepage.php', { style: pop}, function(data) {
$('#tube').html(data);
});
});
});
Just another way to do the same thing as the 2 other answers without binding your click method at page load. Simply set your onclick attribute on your list item to a function containing your ajax call. This is easier to follow in my opinion.
<script type="text/javascript" >
function makeAJAXPost(){
var pop = 'pop';
$.post('ajax_file.php', {
style: pop
}, function(data) {
$('#tube').html(data);
});
}
</script>
<ul>
<li onclick="makeAJAXPost()" id="pop">Pop</li>
</ul>

How to use divs as radio button selectors for hidden field with jquery?

I'm trying to create a good looking product order form with jquery skills.
I have some shoe size values as like divs:
<div id="select-size">
<div id="size-value-19">39</div>
<div id="size-value-20">40</div>
<div id="size-value-21">41</div>
<input type="hidden" name="option[229]" id="option-size" value="">
</div>
When a customer clicks on a shoe size numbers it should take the size-value-?? part from div id and put it into #option-size hidden field.
How can I do that?
BTW: I had found a prototypejs example for this work but prototype and jquery can't work together properly.
Let me give the prototype example code for you:
<script type="text/javascript">
//<![CDATA[
document.observe("dom:loaded", function() {
function deActivate(elt) {
elt.removeClassName('active');
}
function watchClick(evt) {
var element = Event.element(evt);
if (element.hasClassName('outstock')) return;
$$('#select-size div').each(function(elt) {deActivate(elt)});
element.addClassName('active');
var eid = element.id.split('-')[2];
$('option-size').setValue(eid);
}
$$('#select-size div').invoke('observe', 'click', watchClick);
});
//]]>
</script>
I still can't believe that how js framework developers use same $ sign...
$('div').click(function(){
var id = $(this).attr('id');
$('#option-size').val(id);
});
Code presented by OP, translated to jQuery:
$(function() { // On DOM ready ...
var $sizes = $('#select-size div'), // Size elements
$input = $('#option-size'); // Hidden input
$sizes.click(function() { // On click on size element ...
var $this = $(this); // Reference to this element
if (!$this.hasClass('outstock')) { // If not out of stock ...
$sizes.removeClass('active'); // Remove .active on all
$this.addClass('active'); // Add .active on this
$input.val(this.id.split('-')[2]); // Set value in hidden field
}
});
});
(Updated demo)
On a general note:
You should be able to suppress jQuery's use of the $ symbol via the .noConflict() setting. However, it is advisable to translate the functionality into jQuery if this library is already present and you have no other use for prototypejs.
add jquery
<script type="text/javascript" src="script/jquery-1.5.1.js"></script>
and add this script to your page
<script type="text/javascript">
$(document).ready(function () {
$('#size-value-19').click(function () {
$('#option-size').val($(this).text());
});
$('#size-value-20').click(function () {
$('#option-size').val($(this).text());
});
$('#size-value-21').click(function () {
$('#option-size').val($(this).text());
});
});
</script>