I will preface this question with the fact that I am extremely new to HTML and CSS.
I currently have an engineering page at my company I have inherited that has a ton of links. I have organized into some general categories. However, it has been expressed that they would love a searchbox to search links.
I do not have PHP available to me due to circumstances out of my control. What I do have is all the links in my index.html file with the text they display associated with them.
My thought it that I can create the engine such that it recognizes the tag, and then searches the "name" associated with the link in the tag. However, I really have no idea where to start in terms of implementing such a script.
Of course, there may be a much easier way. I am open to any new approaches. I am not biased toward any programming method or language. Thank you so much for the help everyone, and I can provide any other non-NDA information I can.
I would look at the jQuery UI Automcomplete library http://jqueryui.com/demos/autocomplete/, specifically the custom data demo.
I imagine the code something like this (note this is untested and definitely not complete for your purposes):
<head>
<script type='text/javascript'>
var urls = [
{
value: "url-text",
label: "URL Text",
desc: "URL"
},
{
value: "url2-text",
label: "URL2 Text",
desc: "URL2"
}
];
$('#search').autocomplete({
minLength: 0,
source: urls,
focus: function (event, ui) {
$('#search').val(ui.item.label);
return false;
},
select: function (event, ui) {
$('#search').val(ui.item.label);
$('#url').val(ui.item.desc);
return false;
}
})
.data ("autocomplete")._renderItem= function(ul,item) {
return $('<li></li>")
.data( 'item.autocomplete', item )
.append( '<a>' + item.label + '<br />' + item.desc + '</a>' )
.appendTo( ul );
};
</script>
</head>
<body>
<input id="search" />
<p id='url'></p>
</body>
Doing it this way does mean you have to keep a separate list of URLs and text in a javascript variable.
You'll need to include jQuery in your index.html.
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js' />
Give each link a common class. You can then use jQuery to find the link the user is searching for:
var search = $("#searchBox").val();
$("a.myLinks[href*="+search+"]"); // uses jQuery to select the link, see jQuery selectors
Now you can do things with that link, like show it or navigate to it.
Related
I have a web application with a HTML Action link. My requirement is to have a mouse hover / Tool tip to the action link where the details of corresponding HTML Action links has to be displayed when mouse is placed over the link.
Following is the HTML Action link
<td> #Html.ActionLink(#item.Split('.')[0], "myMethod", new { name = item }, new { Class = "action add", title ="My Tooltip"})</td>
I want to call a method from here that returns the corresponding details and the details has to be shown as a tool tip to the users.
Help me in resolving this issue.Thanks in advance!!!
Here is the JQuery plugin to do a Tooltip. It will attach to the control's title attribute as you would like.
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
$( document ).tooltip();
} );
</script>
Codepen example: https://codepen.io/anon/pen/xmOaKJ
For the dynamic piece and with the assumption your model has a Title property, you should be able to handle it like so:
#Html.ActionLink(#item.Split('.')[0], "myMethod", new { name = item }, new { #class = "action add", #title = item.Title})
I have written the following piece of code to display some contents in angular material dialog box. it works fine when i add plain text to textContent . when i add HTML its displays HTML as text. how do i bind HTML to textContent
This Works
Sample Link
$scope.Modal = function () {
$mdDialog.show(
$mdDialog.alert()
.parent(angular.element(document.querySelector('body')))
.clickOutsideToClose(true)
.textContent('sample text')
.ok('Ok')
);
}
This Doesn't Works
Sample Link
$scope.Modal = function () {
$mdDialog.show(
$mdDialog.alert()
.parent(angular.element(document.querySelector('body')))
.clickOutsideToClose(true)
.textContent('<div class="test"><p>Sample text</p></div>')
.ok('Ok')
);
}
Thanks in advance
You need to append to the template,
$mdDialog.show({
parent: angular.element(document.body),
clickOutsideToClose: true,
template: '<md-dialog md-theme="mytheme">' +
' <md-dialog-content>' +
'<div class="test"><p>Sample text</p></div>' +
' <md-button ng-click="closeDialog();">Close</md-button>' +
' </md-dialog-content>' +
'</md-dialog>',
locals: {
},
controller: DialogController
});
DEMO
You can add html in template and just add variable in displayOption. This will work.
Template Code
<script type="text/ng-template" id="confirm-dialog-answer.html">
<md-dialog aria-label="confirm-dialog">
<form>
<md-dialog-content>
<div>
<h2 class="md-title">{{displayOption.title}}</h2>
<p>{{displayOption.content}} <img src="{{displayOption.fruitimg}}"/></p>
<p>{{displayOption.comment}}</p>
</div>
</md-dialog-content>
<div class="md-actions" layout="row">
<a class="md-primary-color dialog-action-btn" ng-click="cancel()">
{{displayOption.cancel}}
</a>
<a class="md-primary-color dialog-action-btn" ng-click="ok()">
{{displayOption.ok}}
</a>
</div>
</form>
</md-dialog>
</script>
Controller Code
$mdDialog.show({
controller: 'DialogController',
templateUrl: 'confirm-dialog-answer.html',
locals: {
displayOption: {
title: "OOPS !!",
content: "You have given correct answer. You earned "+$scope.lastattemptEarnCount,
comment : "Note:- "+$scope.comment,
fruitimg : "img/fruit/"+$scope.fruitname+".png",
ok: "Ok"
}
}
}).then(function () {
alert('Ok clicked');
});
Use template instead of textContent, textContent is used for show plan text in a model. It does not render HTML code
$mdDialog.show({
controller: function ($scope) {
$scope.msg = msg ? msg : 'Loading...';
},
template: 'div class="test"><p>{{msg}}</p></div>',
parent: angular.element(document.body),
clickOutsideToClose: false,
fullscreen: false
});
You can use htmlContent instead of textContent to render HTML. Heres an excerpt from the documentation available at https://material.angularjs.org/latest/#mddialog-alert
$mdDialogPreset#htmlContent(string) - Sets the alert message as HTML.
Requires ngSanitize module to be loaded. HTML is not run through
Angular's compiler.
It seems a bit counter intuitive to use a template when you only need to inject one or two things in. To avoid using a template, you need to include 'ngSanitize' for it to work.
angular.module('myApp',['ngMaterial', 'ngSanitize'])
.controller('btnTest',function($mdDialog,$scope){
var someHTML = "<font>This is a test</font>";
$scope.showConfirm = function(ev) {
// Appending dialog to document.body to cover sidenav in docs app
var confirm = $mdDialog.confirm()
.title('Please confirm the following')
.htmlContent(someHTML)
.ariaLabel('Lucky day')
.targetEvent(ev)
.ok('Please do it!')
.cancel('Sounds like a scam');
//Switch between .htmlContent and .textContent. You will see htmlContent doesn't display dialogbox, textContent does.
$mdDialog.show(confirm).then(function() {
$scope.status = 'Saving Data';
},
function() {
$scope.status = 'You decided to keep your debt.';
});
};
})
Notice the injected HTML:
var someHTML = "<font>This is a test</font>";
I found this example here.
The latest version of Angular Material Design API has predefined function for add HTML content to the alert dialog:
an $mdDialogPreset with the chainable configuration methods:
$mdDialogPreset#title(string) - Sets the alert title.
$mdDialogPreset#textContent(string) - Sets the alert message.
$mdDialogPreset#htmlContent(string) - Sets the alert message as HTML. Requires ngSanitize module to be loaded. HTML is not run through Angular's compiler.
$mdDialogPreset#ok(string) - Sets the alert "Okay" button text.
$mdDialogPreset#theme(string) - Sets the theme of the alert dialog.
$mdDialogPreset#targetEvent(DOMClickEvent=) - A click's event object. When passed in as an option, the location of the click will be used as the starting point for the opening animation of the the dialog.
The link to the documentation: Angular MD API
The HTML script tag can be used to define named templates:
<script type="text/html" id="Lookup">
<label class="field-title" data-bind="text: Metadata.FieldTitle, css: { hasError: !IsValid() }"></label>
<div data-bind="html: Metadata.FieldIntro"></div>
<select class="form-control" data-bind="attr: { id: 'ff' + Metadata.FormFieldID }, options: Lookup, optionsText: 'Caption', optionsValue: 'Id', optionsCaption: Metadata.FieldIntro || 'Select an item...', value: Value, css: { hasError: !IsValid() }"></select>
</script>
According to MDN and msdn, I should be able to move the content of a template into a file and reference it like this:
<script type="text/html" id="Lookup" src="Lookup.html"></script>
According to Fiddler template files are being loaded (I have several). What stops knockout from using the templates when they aren't inline, and is there anything that can be done about it?
From the comments, script tags don't parse what they load into the DOM. I could use something like jQuery ajax to load, parse and inject but knockout uses the script node's id to reference the template, so the next question is how to make visible the fragment so loaded.
At a stab I surmise that I need to do something like this:
$(document.body)
.append("<div id='Lookup' style='display:none'></div>")
.load("Templates/Lookup.html" );
Close, but no cigar. Here it is corrected and wrapped up as a function:
function loadTemplate(name) {
if (name)
switch (name.constructor) {
case String:
$(document.body).append("<div id='" + name + "' style='display:none'></div>");
$("#" + name).load("Templates/" + name + ".html");
break;
case Array:
name.map(loadTemplate);
break;
default:
throw "Must be a string or an array of strings";
}
}
You can pass a single template name or an array of names.
Knockout happily uses the template.
Browsers don't know how to process programs written in text/html (yes, that sentence doesn't make a whole lot of sense, this is a hack you are using).
Whatever JavaScript you are using to process the templates is reading the childnodes of the script element in the DOM. It hasn't been written to check for a src attribute and load external content.
The Situation
Nested within our Angular app is a directive called Page, backed by a controller, which contains a div with an ng-bind-html-unsafe attribute. This is assigned to a $scope var called 'pageContent'. This var gets assigned dynamically generated HTML from a database. When the user flips to the next page, a called to the DB is made, and the pageContent var is set to this new HTML, which gets rendered onscreen through ng-bind-html-unsafe. Here's the code:
Page directive
angular.module('myApp.directives')
.directive('myPage', function ($compile) {
return {
templateUrl: 'page.html',
restrict: 'E',
compile: function compile(element, attrs, transclude) {
// does nothing currently
return {
pre: function preLink(scope, element, attrs, controller) {
// does nothing currently
},
post: function postLink(scope, element, attrs, controller) {
// does nothing currently
}
}
}
};
});
Page directive's template ("page.html" from the templateUrl property above)
<div ng-controller="PageCtrl" >
...
<!-- dynamic page content written into the div below -->
<div ng-bind-html-unsafe="pageContent" >
...
</div>
Page controller
angular.module('myApp')
.controller('PageCtrl', function ($scope) {
$scope.pageContent = '';
$scope.$on( "receivedPageContent", function(event, args) {
console.log( 'new page content received after DB call' );
$scope.pageContent = args.htmlStrFromDB;
});
});
That works. We see the page's HTML from the DB rendered nicely in the browser. When the user flips to the next page, we see the next page's content, and so on. So far so good.
The Problem
The problem here is that we want to have interactive content inside of a page's content. For instance, the HTML may contain a thumbnail image where, when the user clicks on it, Angular should do something awesome, such as displaying a pop-up modal window. I've placed Angular method calls (ng-click) in the HTML strings in our database, but of course Angular isn't going to recognize either method calls or directives unless it somehow parses the HTML string, recognizes them and compiles them.
In our DB
Content for Page 1:
<p>Here's a cool pic of a lion. <img src="lion.png" ng-click="doSomethingAwesone('lion', 'showImage')" > Click on him to see a large image.</p>
Content for Page 2:
<p>Here's a snake. <img src="snake.png" ng-click="doSomethingAwesone('snake', 'playSound')" >Click to make him hiss.</p>
Back in the Page controller, we then add the corresponding $scope function:
Page controller
$scope.doSomethingAwesome = function( id, action ) {
console.log( "Going to do " + action + " with "+ id );
}
I can't figure out how to call that 'doSomethingAwesome' method from within the HTML string from the DB. I realize Angular has to parse the HTML string somehow, but how? I've read vague mumblings about the $compile service, and copied and pasted some examples, but nothing works. Also, most examples show dynamic content only getting set during the linking phase of the directive. We would want Page to stay alive throughout the life of the app. It constantly receives, compiles and displays new content as the user flips through pages.
In an abstract sense, I guess you could say we are trying to dynamically nest chunks of Angular within an Angular app, and need to be able to swap them in and out.
I've read various bits of Angular documentation multiple times, as well as all sorts of blog posts, and JS Fiddled with people's code. I don't know whether I'm completely misunderstanding Angular, or just missing something simple, or maybe I'm slow. In any case, I could use some advice.
ng-bind-html-unsafe only renders the content as HTML. It doesn't bind Angular scope to the resulted DOM. You have to use $compile service for that purpose. I created this plunker to demonstrate how to use $compile to create a directive rendering dynamic HTML entered by users and binding to the controller's scope. The source is posted below.
demo.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="angular.js#1.0.7" data-semver="1.0.7" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js"></script>
<script src="script.js"></script>
</head>
<body>
<h1>Compile dynamic HTML</h1>
<div ng-controller="MyController">
<textarea ng-model="html"></textarea>
<div dynamic="html"></div>
</div>
</body>
</html>
script.js
var app = angular.module('app', []);
app.directive('dynamic', function ($compile) {
return {
restrict: 'A',
replace: true,
link: function (scope, ele, attrs) {
scope.$watch(attrs.dynamic, function(html) {
ele.html(html);
$compile(ele.contents())(scope);
});
}
};
});
function MyController($scope) {
$scope.click = function(arg) {
alert('Clicked ' + arg);
}
$scope.html = '<a ng-click="click(1)" href="#">Click me</a>';
}
In angular 1.2.10 the line scope.$watch(attrs.dynamic, function(html) { was returning an invalid character error because it was trying to watch the value of attrs.dynamic which was html text.
I fixed that by fetching the attribute from the scope property
scope: { dynamic: '=dynamic'},
My example
angular.module('app')
.directive('dynamic', function ($compile) {
return {
restrict: 'A',
replace: true,
scope: { dynamic: '=dynamic'},
link: function postLink(scope, element, attrs) {
scope.$watch( 'dynamic' , function(html){
element.html(html);
$compile(element.contents())(scope);
});
}
};
});
Found in a google discussion group. Works for me.
var $injector = angular.injector(['ng', 'myApp']);
$injector.invoke(function($rootScope, $compile) {
$compile(element)($rootScope);
});
You can use
ng-bind-html https://docs.angularjs.org/api/ng/service/$sce
directive to bind html dynamically.
However you have to get the data via $sce service.
Please see the live demo at http://plnkr.co/edit/k4s3Bx
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope,$sce) {
$scope.getHtml=function(){
return $sce.trustAsHtml("<b>Hi Rupesh hi <u>dfdfdfdf</u>!</b>sdafsdfsdf<button>dfdfasdf</button>");
}
});
<body ng-controller="MainCtrl">
<span ng-bind-html="getHtml()"></span>
</body>
Try this below code for binding html through attr
.directive('dynamic', function ($compile) {
return {
restrict: 'A',
replace: true,
scope: { dynamic: '=dynamic'},
link: function postLink(scope, element, attrs) {
scope.$watch( 'attrs.dynamic' , function(html){
element.html(scope.dynamic);
$compile(element.contents())(scope);
});
}
};
});
Try this element.html(scope.dynamic);
than element.html(attr.dynamic);
I'm a newbie to all this ASP.NET MVC stuff, and I was making some tests for my project. I wanted to ask how is it possible to introduce a javascript function call from the html.radiobutton function. For example, how would you declare this:
<input type="radio" name = "Kingdom" value = "All" onclick="GetSelectedItem(this);" checked ="checked" />
with html.radiobutton. I've been looking for some documentation, but I don't really get to understand, I guess it has something to do with the html object attributes, but don't really know the syntax and I haven't found any example.
Thank you all in advance :)
vikitor
Define the attributes as an anonymous object.
<%= Html.Radiobutton( "Kingdom",
"All",
true,
new { onclick = "GetSelectedItem(this);" } ) %>
or better yet, apply the handler unobtrusively with javascript (ex. uses jQuery).
<%= Html.RadioButton( "Kingdom", "All", true ) %>
<script type="text/javascript">
$(function() {
$('input[name=Kingdom]').click( function() {
GetSelectedItem(this); // or just put the code inline here
});
});
</script>