Displaying json data via angular - javascript

I have created a datatable showing a list of persons and their details. When the datatable is clicked, it has to show the entity of the single person with their details but my problem is, when I click the datatable it is opening a chat box showing the entity of the last clicked person changing all other chat box details.
1.How can I limit the append directive, that is, one chatbox for one id?
2.How to display the name of the particular person without changing the older chat box entity?
Here is the link to Plunker http://plnkr.co/edit/VTWcZQjlAda0KQ9sjFzI?p=preview

Actually i really think there is no need for a directive here.
It can simply be done by using ng-repeat and a collection.
See it working in this plunker
I added this in the controller :
$scope.bottomListCollection = [];
$scope.addToBottomList = function(artist) {
$scope.bottomListCollection.push(artist);
}
And this kind of ng-click on your rows :
ng-click="addToBottomList(item)"
Some advices to do things cleaner in angular :
Never use :
$compile.
$element.
$broadcast.
Jquery.
Take care of custom directives, theses are 90% miss-used.
Just a reminder : Directives are intended to add a behavior on an element. Not adding html.
Hope it helped.

Some tips that fix your issue
childScope = $scope.$new(true);
to ve an isolated scope you ve to use the first parameter of $new method
for more info look at the docs ($new(isolate, parent); --> https://docs.angularjs.org/api/ng/type/$rootScope.Scope)
then you need to add a control on the AppendText function like this to check if the same chat already exist
$scope.AppendText = function(idx) {
$scope.userInfo = $scope.artists[idx];
var chat = $('#chat_'+$scope.userInfo.shortname);
console.log(chat);
if ($scope.stage === 'Add' && chat.length==0 ) {
childScope = $scope.$new(true);
childScope.userInfo = $scope.userInfo; //<--- add old scope info to new scope
var compiledDirective = $compile('<div my-directive></div>');
var directiveElement = compiledDirective(childScope);
$('.my-directive-placeholder').append(directiveElement);
} else {
$scope.stage = 'Add';
}
}
working plunker http://plnkr.co/edit/TFjlN0U2i4irKtG2D5yu?p=preview

To answer the second part of your question : Create an isolate scope!
That can be done by passing true while creating a new scope: childScope = $scope.$new(true).
Once the isolate scope is created, you can do:
childScope.userInfo = $scope.userInfo;
PLUNK : http://plnkr.co/edit/IxPh4EmLpr8WAqRWtRlo?p=preview
Also, a hackish solution using one time databinding (not recommended):
http://plnkr.co/edit/RjZNOSyaemqg2eZ4Gma1?p=preview
To answer the first part: You could keep track of the id's that are passed to the $scope.AppendText function perhaps?
PLUNK: http://plnkr.co/edit/BCNju0rToyVYvNjqzVON?p=preview
Hope this helps! IMHO it would be much more simpler if you could just ng-repeat over your json data to generate the chatboxes.

Related

Style node of Dabeng's OrgChart library

I am using the Dabeng Orgchart library, but I would like to customize the nodes, specifically creating a diamond instead of the squares they have in most examples. I have seen the createNode method, and I have found various CSS for creating a diamond but I can't figure out how to integrate it in dabeng org chart. What I want to do is display a diamond if some conditions are met, and the default square shapes if others are met. I have searched the web, but no example for changing the shape.
I am currently using the nodeTemplate attribute for the orgchart. Example:
var oc = $('#container').orgchart({
...
'nodeTemplate': orgTemplate,
...
});
In your orgtemplate function, data is whatever you have included in your orgchart data (in the example it would be name and title). You can stuff this object with other flags. For example, I have a chart in which I create new nodes and allow users to enter data into the node before committing it to the graph. I have a flag in my data object for data.isSaved to tell my template whether or not this node is saved or not. If it is saved, I have inline html checks (in AngularJS using ngIf's and the like, if you're familiar with AngularJS at all) to change the template based on the data.
In VanillaJS, you can just return pure HTML without the $compile and all that attached to pump in your own node template. You could actually do your check within the function for example:
function orgTemplate(data) {
if(data.isDiamond) {
return '<div class="diamond">...</div>';
} else {
return '<div class="square">...</div>';
}
}
I'm using AngularJS in my website so I define new scopes and use angular directives to make it more expandable. This is for reference for anyone else who stumbles upon this. My orgTemplate function is defined below.
function orgTemplate(data) {
var newScope = $scope.$new(true);
newScope.data = data;
return ( $compile('<div data-ng-include="\'.../template.html\'"></div>')(newScope));
}
Here's the orgChart Github as I'm sure you've browsed many times. If you look at the bottom you will see the nodeTemplate attribute definition I mention above. Hope this helps!
Side Note: I have had some trouble with styling when using custom templates, especially when defining different graph directions (i.e. 'l2r').
You can now customize your own node structure or shape with option "ndoeTemplate":
var nodeTemplate = function(data) {
return `
<span class="office">${data.office}</span>
<div class="title">${data.name}</div>
<div class="content">${data.title}</div>
`;
}
var oc = $('#chart-container').orgchart({
'data' : ds,
'nodeTemplate': nodeTemplate
});
Feel free to play around with this demo.
I would suggest you to use getorgchart instead it is highly customizable
http://www.getorgchart.com/Demos/Create-Your-Own-Theme-4

angularjs share data between controllers (service approach) - watcher is no called

I'm struggling with sharing data between controllers with the service approach in angularjs. From somewhere here on stackoverflow I got this working code (sorry, I miss the original source) and I extendet it.
jsbin sourcecode
(updatet version: http://jsbin.com/hadegec/5/edit?html,js,output)
All is working fine with the original source, adding items to cart and the total price is updated in the CartCtrl.
I tried to extend it with a very simple message. But while the items watcher works very fine, the watcher to my new messageCart is not working. I really cannot see the difference between the items update and my new message test. It must be the watcher, because if I set the $scope.messageCart inside the item-watcher (console.log("w-Items:"+Order.getmessage()); I allways get the correct string...
Any idea?
The solution is:
not watch on (unchagend) message string property of scope
$scope.ordernewmessage = Order.getOrderMessage();
$scope.$watch('ordernewmessage ', function() {
but watch a function return the service property
$scope.$watch(function(){return Order.message;}, function(){
The last thing I don't understand is the difference betweeen the array property 'items' and the string propery 'message'. I don't understand, why the '$scope.itemsCart' reference to 'Order.items' is detected as changed while the '$scope.ordernewmessage' set like this; '$scope.ordernewmessage = Order.getOrderMessage()' is not changed...

Getting external variables inside Angular.js factory

I am giving my first steps with Angular.js and I am facing a little problem which I don't know how to deal with Angular. I know many jQuery ways for solving it, but I am sure that it may exists an Angular way:
Firstly, I have an select element set with currentPlant as ng-model
<select class="form-control" name="planta" ng-model='currentPlant' ng-options='plant.name for plant in plants' >
</select>
I print the current name as page title, I see this element updating when I change the selected value, so I am sure that currentPlant is being correctly updated.
<h1>{{ currentPlant ? currentPlant.name : 'Seleccione una planta'}}</h1>
Now I have the following button:
<button class='btn btn-primary' ng-click='loadTowers()'>
Cargar torres
</button>
When the button is pressed, the loadTowers function is executed, and is now when the problems start. I have set the loadTowers function in the controller that way:
$scope.loadTowers = plants.towers;
plant is a angular service which has implemented the towers function inside. I need to get the value of currentPlant inside this function. Take a look:
.factory('plants', ['$http',function($http){
var o = {
plants: [],
towers : []
};
o.towers = function(){
var id = ¿?; // I NEED SET THIS VARIABLE WITH THE currentPlant.id VALUE
$http.get('/api/v1/plants/'+id+'/towers')
.success(function(data){
angular.copy(data, o.towers);
})
}
return o;
}]);
I could set an data-plant attribute in the option element, and get the selected through jQuery, but I am trying avoid this kind of solutions. How do you deal with this?
NOTE: Take account that I simply want get the option selected when I press the button and make different get requests to the API`in function of that through the service.
Thanks in advance.
Pass the value in the ngclick:
<button ng-click='loadTowers(currentPlant)'>
Then add it in the factory args:
o.towers = function(currentPlant){
}

check if directive with given name exists, angularjs

Is there a way of checking if an directive in angular exists?
What I want to do, oder better what I have:
A Collection of 'protocols', which share some similarities, such as: name, created by, last edited, comment etc., but they all have special fields.
I have this one directives which matches with all those protocols. Showing the name and all the things which all the protocol have in common.
Within this directive I want to check if a special (more specific) view of the given protocol is available. In my case I call it "CompactView". The CompactView will give more detailed information of this protocol, it should be displayed within the actual directives. So a nested directive - no big deal.
My first approched worked fine, I had an array which had the protocol name as key, and directive html element (string) as value:
let decider = {
'cardiovascular_function': '<hcd-Cardiovascular-Function-Compact-View protocol="protocol"/>'
};
//use suitable directive
let protocolDirective = decider[scope.protocol.name];
let templateHook = angular.element(element).find('.extend-protocol-info')[0];
//use base template
//hooks protocol directive into template if possible
if (typeof protocolDirective != 'undefined') {
let compiled = $compile(angular.element(protocolDirective))(scope);
angular.element(templateHook).html(compiled);
scope.defaultTxt = false;
}else{
scope.defaultTxt = true;
}
If no key exited within the decider array I will display some default txt explaining, that there is no CompactView available.
The application will likely grow, and a lot of protocols will follow, so when ever someone creates a protocol the decider array needs to be extend. Prone to failure, and it would be much nicer if I can just check if a directive with some name exists and compile it.
My new approached look like the following:
let protocolName = scope.protocol.name;
let directiveName = 'hcd' + _.capitalize(_.camelCase(protocolName)) + 'CompactView';
//example: <hcd-Cardiovascular-Function-Compact-View protocol="protocol"/>
console.log(directiveName);
console.log($injector.has(directiveName));
try {
console.log(angular.module('hcdProtocol').directive(directiveName));
} catch (err) {
console.log(err);
}
//check if directive for given protocol exists
if ($injector.has(directiveName)) {
scope.defaultTxt = false;
let templateHook = angular.element(element).find('.extend-protocol-info')[0];
let protocolDirective = '<hcd-' + _.kebabCase(protocolName) + '-Compact-View protocol="protocol" />';
let compiled = $compile(angular.element(protocolDirective))(scope);
angular.element(templateHook).html(compiled);
} else {
//display default if no compact view exists
scope.defaultTxt = true;
}
So $injector.has is not working, since directives are not registered within $provide. Redeclaring and checking for errors, the try catch block, is not working either.
I'm currently trying to understand $compileProvider, somewhere within angular is the information which directive exist, I would love to find it.
Any ideas or suggestions, on how to fix this "generic directive" approach?
Maybe my concept with this nested directives is wrong, and there is a much simpler approach?
Both code blocks are within the link function of directive()

Prototyping an Angular Directive

Based on instruction from this question, I have added the following code to my application within the config stage:
$provide.decorator('formDirective', function($delegate) {
var directive = $delegate[0];
directive.controller.prototype.inputs = {};
console.log(directive.controller);
return $delegate;
});
All I want to do is create another field and a few methods to the existing angular form object. All of that appears to be defined within the formDirective controller but when I prototype new fields and methods into that controller they are not available after my application is completed bootstrapping. Is there something I'm missing, is this even possible without modifying the source?
Thanks in advance!
EDIT Code Pen of Design Patterns Here
http://codepen.io/anon/pen/EadRBo
Thanks for your help. I did get this working and if your curious, this is why it was so important:
$provide.decorator('formDirective', function($delegate) {
var directive = $delegate[0];
directive.controller.prototype.$validate = function () {
var form = this;
var p;
for(p in form) {
if(form.hasOwnProperty(p) && p.indexOf('$') < 0) {
form[p].$setTouched();
}
}
};
A simple way to mark every element as touched causing the fields to be invalidated and error logic to kick in. I wanted this when a form was attempted to be submitted so that the user could see all the fields that were required. This also helps to keep my controllers slim without the extra overhead of an additional service.

Categories

Resources