I was trying to write a simple directive to generate a (potentially) more complex dom element. I am quite confused about what is going on here but I think the directive I use inside my directive get linked first? Anyway the element I am generating is not visible where it should.
Sorry for all that confusion, here is the plunkr:
http://plnkr.co/edit/vWxTmA1tQ2rz6Z9dJyU9?p=preview
I think the directive I use inside my directive get linked first?
Yes. A child directive's link function will execute before the parent's link function.
Here is a fiddle that shows two nested directives,
<div d1>
<div d2></div>
</div>
and it logs when the directives' controller and link functions are called.
There are a few issues with your Plunker:
Since you are using # for your isolate scopes, you need to use {{}}s in your attribute values:
<visible value='{{visible}}'>plop</visible>
<invisible value='{{visible}}'>plop</invisible>
Since $scope.visible is defined in your controller, I assume you meant to use that value, and not test.
In the invisible directive, you need to use isolate scope property value in your link function. Property visible is available to the transcluded scope (which is in affect if you use a template in your directive like #Langdon has) but not the isolate scope, which is what the link function sees.
var template = "<span ng-show='value'>{{value}}</span>";
Plunker.
If you want a simple directive, you're better off letting Angular do most of the work through ngTransclude, and $watch.
http://plnkr.co/edit/xYTNIUKYuHWhTrK80qKJ?p=preview
HTML:
<!doctype html>
<html ng-app="app">
<head>
<meta charset="utf-8">
<title>trying to compile stuff</title>
<script src="http://code.angularjs.org/1.1.1/angular.js"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller="AppCtrl">
<input type="checkbox" ng-model="test" id="test" /><label for="test">Visibility (currently {{test}})</label>
<br />
<br />
<visible value='test'>visible tag</visible>
<invisible value='test'>invisible tag</invisible>
</div>
</body>
</html>
JavaScript:
angular
.module('app', [])
.controller('AppCtrl', function($scope) {
$scope.test = false;
})
.directive('visible', function() {
return {
restrict: 'E',
transclude: true,
template: '<span ng-transclude></span>',
replace: true,
scope: {
value: '='
},
link: function(scope, element, attrs) {
console.log(attrs);
scope.$watch('value', function (value) {
element.css('display', value ? '' : 'none');
});
console.log(attrs.value);
}
};
})
.directive('invisible', function() {
return {
restrict: 'E',
transclude: true,
template: '<span ng-transclude></span>',
replace: true,
scope: {
value: '='
},
link: function(scope, element, attrs) {
scope.$watch('value', function (value) {
element.css('display', value ? 'none' : '');
});
}
};
});
Related
According to the polymer documentation for app-localize-behavior
Each element that displays content to be localized should add Polymer.AppLocalizeBehavior. All of these elements share a common localization cache, so you only need to load translations once.
In the following snippet (adapted from this answer) does not find the shared resources in the tag
Maybe I missed something ?
<!DOCTYPE html>
<html>
<head>
<base href="https://polygit.org/polymer+:master/components/">
<script src="webcomponentsjs/webcomponents-lite.min.js"></script>
<script src="https://rawgit.com/yahoo/intl-messageformat/d361003/dist/intl-messageformat.min.js"></script>
<link rel="import" href="polymer/polymer.html">
<link rel="import" href="paper-toggle-button/paper-toggle-button.html">
<link rel="import" href="app-localize-behavior/app-localize-behavior.html">
</head>
<body>
<x-local-translate></x-local-translate>
<dom-module id="x-local-translate">
<template>
<div>
<span title="english">🇬🇧</span>
<paper-toggle-button on-change="_toggle" id="switch"></paper-toggle-button>
<span title="french">🇫🇷</span>
</div>
<div>
<h4>Outside Repeater</h4>
<div>
<div>{{localize('greeting')}}</div>
</div>
<h4>Template Repeater Items</h4>
<template is="dom-repeat" items="{{things}}">
<div>{{localize('greeting')}}</div>
</template>
<x-local-test></x-local-test>
</div>
</template>
<script>
Polymer({
is: "x-local-translate",
behaviors: [
Polymer.AppLocalizeBehavior
],
properties: {
things: {
type: Array,
value: function() {
return [1, 2, 3];
}
},
/* Overriden from AppLocalizeBehavior */
language: {
value: 'en',
type: String
},
/* Overriden from AppLocalizeBehavior */
resources: {
type: Object,
value: function() {
return {
'en': {
'greeting': 'Hello!'
},
'fr': {
'greeting': 'Bonjour!'
}
};
}
}
},
_toggle: function() {
this.language = this.$.switch.checked ? 'fr' : 'en';
}
});
</script>
</dom-module>
<dom-module id="x-local-test">
<template>
<h4>Inside x-local-test</h4>
<div>{{localize('greeting')}}</div>
</template>
<script>
Polymer({
is: "x-local-test",
behaviors: [
Polymer.AppLocalizeBehavior
],
properties: {
things: {
type: Array,
value: function() {
return [1, 2, 3];
}
}
},
});
</script>
</dom-module>
</body>
</html>
Now in the following fiddle, I made it work by passing the resources and language object as x-local-test properties.
https://jsfiddle.net/g4evcxzn/2/
But it should work without that
According the ideas of Jose A. and Jean-Rémi here some example code for copy/paste:
<link rel="import" href="../bower_components/polymer/polymer.html">
<link rel="import" href="../bower_components/app-localize-behavior/app-localize-behavior.html">
<script>
MyLocalizeBehaviorImpl = {
properties: {
language: {
value: 'de'
}
},
attached: function() {
this.loadResources(this.resolveUrl('locales.json'));
}
};
MyLocalizeBehavior = [MyLocalizeBehaviorImpl, Polymer.AppLocalizeBehavior];
</script>
Include the behavior file in all your custom components and add the behavior:
<link rel="import" href="./my-localize-behavior.html">
......
behaviors: [
MyLocalizeBehavior
],
I took a look at AppLocaleBehavior's demo and if you actually look at the repo, they use two elements for it, one that loads the resources from an external json and one more that has them locally defined and in the demo, the don't seem to be sharing a cache, just as what's happening to you.
This struck me as odd seeing that they do mention the cache, so I took a look at the behavior's code and found out something interesting, the cache actually exists but it seems its purpose is to prevent loading the same external resource multiple times rather than sharing the resources property.
So, if you want to share localization resources on multiple elements the way to go would be having a common resource (let's say we call it locales.json) and call the loadResources function on every one of them (Since the request is cached you don't need to worry about loading the file multiple times). You could do it on the attached callback like this:
attached: function () {
this.loadResources(this.resolveUrl('locales.json'));
}
Solution Here: http://jsfiddle.net/lookitstony/24hups0e/6/
Crimson's comment lead me to a solution.
I am having an issue with KO and the Jquery UI dialog. The dialogs are not being destroyed with the template that loaded them.
I was previously storing an instance of the dialog and reusing it over and over without using the binding handler. After reading a few posts about the included binding handler I felt perhaps that was the best way to handle the dialogs. Am I using knockout wrong? Should I stick with the stored reference or does KO have a better way to handle this? If this was an SPA, how would I manage this if I was swapping between pages that may or may not have these dialogs?
You can witness this behaviour by checking out my example here: http://jsfiddle.net/lookitstony/24hups0e/2/
JAVASCRIPT
(function () {
ko.bindingHandlers.dialog = {
init: function (element, valueAccessor, allBindingsAccessor) {
var options = ko.utils.unwrapObservable(valueAccessor()) || {};
setTimeout(function () {
options.close = function () {
allBindingsAccessor().dialogVisible(false);
};
$(element).dialog(options);
}, 0);
//handle disposal (not strictly necessary in this scenario)
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
$(element).dialog("destroy");
});
},
update: function (element, valueAccessor, allBindingsAccessor) {
var shouldBeOpen = ko.utils.unwrapObservable(allBindingsAccessor().dialogVisible),
$el = $(element),
dialog = $el.data("uiDialog") || $el.data("dialog");
//don't call open/close before initilization
if (dialog) {
$el.dialog(shouldBeOpen ? "open" : "close");
}
}
}
})();
$(function () {
var vm = {
open: ko.observable(false),
content: ko.observable('Nothing to see here...'),
templateOne: ko.observable(true),
templateTwo: ko.observable(false),
templateOneHasDialog: ko.observable(true),
showOne: function(){
this.templateTwo(false);
this.templateOne(true);
},
showTwo: function(){
this.templateOne(false);
this.templateTwo(true);
},
diagOpt: {
autoOpen: false,
position: "center",
modal: true,
draggable: true,
width: 'auto'
},
openDialog: function () {
if(this.templateOneHasDialog()){
this.content('Dialog opened!');
this.open(open);
} else {
this.content('No Dialog Available');
}
}
}
ko.applyBindings(vm);
});
HTML
<div id='ContentContainer'>
Experience Multiple Dialogs
<ul>
<li>Click "Open Dialog"</li>
<li>Move the dialog out of the center and notice only 1 dialog</li>
<li>Close Dialog</li>
<li>Now click "One" and "Two" buttons back and forth a few times</li>
<li>Now click "Open Dialog"</li>
<li>Move the dialog and observe the multiple dialogs</li>
</ul>
<button data-bind="click:showOne">One</button>
<button data-bind="click:showTwo">Two</button>
<!-- ko if: templateOne -->
<div data-bind="template:{name:'template-one'}"></div>
<!-- /ko -->
<!-- ko if: templateTwo -->
<div data-bind="template:{name:'template-two'}"></div>
<!-- /ko -->
</div>
<script type="text/html" id="template-one">
<h3>Template #1</h3>
<p data-bind="text:content"></p>
<div><input type= "checkbox" data-bind="checked:templateOneHasDialog" /> Has Dialog </div>
<button data-bind="click:openDialog">Open Dialog</button>
<!-- ko if: templateOneHasDialog -->
<div style="display:none" data-bind="dialog:diagOpt, dialogVisible:open">
The Amazing Dialog!
</div>
<!-- /ko -->
</script>
<script type="text/html" id="template-two">
Template #2
</script>
When using dialog inside template the init method will be called every time when the template is shown and hence multiple dialogs are appeared in your case. To resolve this place the dialog outside the template.
<div style="display:none" data-bind="dialog:diagOpt, dialogVisible:open">
The Amazing Dialog!
</div>
Place this outside the template and now the issue will be resolved.
Updated fiddle: Fiddle
Edit: I went through your code and found that the ko.utils.domNodeDisposal.addDisposeCallback has not been triggered in your case. And hence the dialog has not been destroyed on template change which in returns shows multiple dialog.
But why ko.utils.domNodeDisposal.addDisposeCallback has not called?
The ko.utils.domNodeDisposal.addDisposeCallback will be triggered when the element(rendered using custom binding) in the template is removed from DOM. But in your case, the dialog element is appended to the body instead of template and so it was not triggered
Solution
The jquery ui 1.10.0+ have option to specify where the dialog element has to be appended using appendTo option we can use that to resolve this.
diagOpt: {
autoOpen: false,
position: "center",
modal: true,
draggable: true,
width: 'auto',
appendTo: "#DesiredDivID"
},
<script type="text/html" id="template-one">
<h3>Template #1</h3>
<p data-bind="text:content"></p>
<div><input type= "checkbox" data-bind="checked:templateOneHasDialog" /> Has Dialog </div>
<button data-bind="click:openDialog">Open Dialog</button>
<!-- ko if: templateOneHasDialog -->
<div id="DesiredDivID"></div>
<div id="dlg" data-bind="dialog:diagOpt, dialogVisible:open">
The Amazing Dialog!
</div>
<!-- /ko -->
</script>
Now the dialog element will be appended to the #DesiredDivID and destroyed on template change.
See the updated fiddle: Updated one-April-1
I am working on a web application and was making great progress using JQuery UI Tabs, specifically the 'url' method of dynamically updating the target url of the ajax request which was bound to each tab. I have created a simplified example here:
Each of the 2 Tabs, function 1 & function 2, display the results of some tests based on the parameters that are passed to the test. The tests remain the same throughout, but I was changing the variables used in the functions by manipulating the url bound to the tab. The 'url' method of updating the url being called on a lazy loading Tab allowed me to do this, but its now been deprecated and won't be supported at all soon. So I have been searching for a way to do this using the 'beforeLoad' event in JQuery UI 1.9.
The suggestion was that one could manipulate the ui.ajaxSettings to set the data parameter but there is a bug (http://bugs.jqueryui.com/ticket/8673), and it appears this won't be fixed. The workaround suggested is to manipulate the ui.ajaxSettings.url instead.
My working example is below, but I'm not sure if this is the cleanest / most appropriate way to achieve what I'm after and any suggestions would be most welcome. I struggled to find examples on how to do even this much, so hopefully it will help someone else in a similar situation.
<title> Jquery Tabs AJAX Test</title>
<script type="text/javascript" src="js/jquery-1.8.2.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.9.1.custom.js"></script>
<link rel="stylesheet" type="text/css" href="css/smoothness/jquery-ui-1.9.1.custom.css">
</head>
<body >
<script type=text/javascript>
$(document).ready(function() {
$( '#tabs' ).tabs({ });
$('button.set_variable').click(function() {
var variable = $(this).val();
$( '#tabs' ).tabs({
beforeLoad: function( event, ui ) {
ui.ajaxSettings.url += "&variable=" + variable ;
}
});
var selected_tab = $('#tabs').tabs('option', 'selected');
$( '#tabs' ).tabs("load", selected_tab);
});
})
</script>
<button class="set_variable" value="1">Variable = 1</button>
<button class="set_variable" value="2">Variable = 2</button>
<button class="set_variable" value="3">Variable = 3</button>
<div id="tabs" >
<ul>
<li>Function 1 </li>
<li>Function 2 </li>
</ul>
</div>
</body></html>
N.B. The ajax.php file here just echos back what was passed to it.
<?php
extract($_GET);
var_dump($_GET);
?>
You could do something like this too :
var variable = '';
$( '#tabs' ).tabs({ beforeLoad: function( event, ui ) {
if(variable != '')
ui.ajaxSettings.url += "&variable=" + variable ;
}});
$('button.set_variable').click(function() {
variable = $(this).val();
});
http://jsfiddle.net/DNWzY/1/
I'm using the Dojo Struts2 datetimepicker, But textfield is editable with the keyboard. I want it in readonly.
I know that this question is answered on another thread, but the solution isn't compatible with ie7, wich is required for me.
The solution in the another thread is:
window.onload = function() {
document.getElementsByName("dojo.test")[0].setAttribute("readOnly","true");
}
But, when I try that on IE7, I get a javascript error:
'document.getElementsByName(...).0' is null or not an object
I read about that, and chage it to:
'document.getElementsBy**Id**(...).0'
But I get another error: The object doesn't support that property.
Any suggestions?
I just wondering if I could change the template of the datetimepicker as I did with a simple Struts2 template... That will solve the problem
<script type="text/javascript">
$(document).ready(function() {
makeReadonly();
});
function makeReadonly() {
setTimeout(function () {
$(".calendar").attr('readonly', 'readonly');
}, 1000);
}
</script>
<td>
<sx:datetimepicker name="up_bod" displayFormat="yyyy-MM-dd" cssClass="rounded calendar" >
</sx:datetimepicker>
</td>
Nice Question.
Use following script. This will work in all browsers.
< % # taglib prefix="sd" uri="/struts-dojo-tags" % >
<head>
<sd:head/>
</head>
< script type="text/javascript">
window.onload = function() {
document.getElementById('fromDate').children[1].setAttribute("readOnly","true");
};
</ script>
<sd:datetimepicker name="fromDate" id="fromDate" label="From Date" />
I hope this will work for you.
I'm trying to use jQuery UI's .tabs() to obtain content via AJAX, but the default behavior is to grab the entire page's content. How would I obtain content from a specific #id and/or multiple #id's?
I have a feeling I will need to use the load: event (http://docs.jquery.com/UI/Tabs#event-load), but I need an assist figuring this out.
Example:
The Page with the tabs that is getting and displaying the tabbed content. I have placed #content after the first #the_tabs link to retrieve in an attempt to obtain that specific region of the content, but the entire page is still loaded.
<div id="tabs">
<div id="tabs_display">
</div>
<ul id="the_tabs">
<li><span>1</span></li>
<li><span>2</span></li>
<li><span>3</span></li>
<li><span>4</span></li>
</ul>
</div><!-- /#tabs -->
The page being retrieved by the previous markup:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Remote HTML Page Example</title>
</head>
<body>
<div id="content">
I want this content
</div>
<div id="other_stuff">
Not this content
</div>
</body>
</html>
the JS (for setup purposes):
$(document).ready(function(){
/* Tabs
--------------------*/
$(function() {
var $tabs = $('#tabs').tabs({
});
});
});
In Jquery-UI 1.9, "ajaxOptions" is depreciated; so instead the code below worked for me:
(ref: http://jqueryui.com/upgrade-guide/1.9/#deprecated-ajaxoptions-and-cache-options-added-beforeload-event)
$(function() {
$( "#the_tabs" ).tabs({
beforeLoad: function( event, ui ) {
ui.ajaxSettings.dataType = 'html';
ui.ajaxSettings.dataFilter = function(data) {
return $(data).filter("#content").html();
};
}
});
});
$(document).ready(function(){
/* Tabs
--------------------*/
var $tabs = $('#the_tabs').tabs({
ajaxOptions: {
dataFilter: function(data, type){
return $(data).filter("#content").html();
}
}
});
});
Solution props to Supavisah in #jquery on irc.freenode.net
I have had luck using .find, rather than .filter. Like this:
$(document).ready(function(){
$('#the_tabs').tabs({
ajaxOptions: {
cache : true,
dataFilter: function(data){
return $(data).find('#content');
},
}
});
});