I recently started using the (not so new) components for an old angular app. I'm trying to make some dumb components for trivial stuff like <button/>s and the like.
For some reason, I can't seem to get one way bindings to work!
The level binding in the difficultyButton component (in difficult-button.js) always returns undefined, but the onLevelChosen binding (again, in difficulty-button.js) seems to have the callback that the options component passed to it.
Do any of you see where I might've gone wrong?
Here is a jsbin link demonstrating this problem : http://jsbin.com/rixukuh/11/edit?html,js
Notice how the classes red, green and blue never get applied because they could never catch hold of the value of vm.level.
Also, the console always prints out LEVEL => undefined, irrespective of what button is clicked.
FULL CODE
Here's the full code, if more context is needed.
options.tpl.html
<div class="full-page-cover">
<div class="options-grid">
<!-- some random markup -->
<div class="buttons-grid">
<difficulty-button
level="easy"
on-level-chosen="vm.chooseDifficulty(level)" >
I'm just here for having fun!
</difficulty-button>
<!-- some more `difficulty-buttons` -->
</div>
</div>
</div>
options.js
import angular from 'angular';
import DifficultyButtonModule from './difficulty-button.js';
import template from './options.tpl.html';
class OptionsController {
constructor() { /* ... */ }
chooseDifficulty(level) { /* ... */ }
}
const OptionsModule = angular.module('options', [DifficultyButtonModule.name])
OptionsModule.component('options', {
template,
controller: OptionsController,
controllerAs: 'vm'
});
export default OptionsModule;
difficulty-button.tpl.html
<button
ng-class="[
'uk-button uk-button-large',
{
easy: 'uk-button-default',
medium: 'uk-button-primary',
hard: 'uk-button-danger'
} [ vm.level ]
]"
ng-click="vm.onLevelChosen({ level: vm.level })"
ng-transclude>
</button>
difficulty-button.js
import angular from 'angular';
import template from './difficulty-button.tpl.html';
const DifficultyButtonModule = angular.module('difficultyButton', []);
DifficultyButtonModule.component('difficultyButton', {
template,
bindings: {
level: '<',
onLevelChosen: '&'
},
controllerAs: 'vm',
transclude: true
});
export default DiffButtonModule;
when you do this
level="easy"
you're binding against easy property in your scope (like $scope.easy). Which of course does not exist. If you want to bind against the string value directly from your html, you need to use single quotes
level="'easy'"
and the same for the other levels. That will work fine.
If you still want to use bind against object, you will need to create them in them your scope. But since you need one way only, using string should work fine
Disclaimer: I haven't worked with components, so it might be that the explanation is incorrect. I have just worked with angularjs
Related
I have a ui-view,
<div ui-view="filtersView_ModalA" class="filter-container"></div>
Now, I want to make generic routes, so that going forward, if any new filterView needs to be implemented like say,
<div ui-view="filtersView_ModalB" class="filter-container"></div>
My route can handle the same.
I am getting ModalA or ModalB from stateParams.prodType.
.state('Modal.tabs', {
url: .......,
views: {
'filtersView_{{stateParams.prodType}}#Modal.tabs': {
templateUrl: function(stateParams) {
// stateParams.prodType works here
.....
},
It's not working.
I also tried , 'filtersView_' + stateParams.prodType + '#Modal.tabs' : {
Nothing worked.
Or, can I declare a constant and concat the values in view names?
Am I doing something wrong?
No, you can't compose the view-name.
But you can do that using named views in different states. You can specify which component should be rendered in the view in which state. See more in the documentation: https://github.com/angular-ui/ui-router/wiki/Nested-States-and-Nested-Views
And also this entry: https://github.com/angular-ui/ui-router/wiki/Multiple-Named-Views
I'd like to be able to set custom attributes on the host element for Angular 1.5 components.
Why?
I want to add a class to a component so I can style it. For example, if a component's parent has display: flex set, I'll likely want to set the flex property on the component.
It's often useful to conditionally apply a class depending on a component's state.
In certain circumstances, I'd like to use ARIA attributes to make a component more accessible.
Here's a simplified example of what I'd like to do (it obviously doesn't work, but I'm looking for something similar):
angular.module("app").component('hello', {
attributes() {
return {
class: "hello " + (this.greeting ? "hello--visibile" : ""),
data-greeting: this.greeting
}
},
bindings: {
greeting: "<",
}
})
It looks like Angular 2.0 supports this feature, but I don't see anything in the docs about supporting it in 1.5. Is there a way to accomplish this for those of us still stuck using .component?
In the past, I would have simply used replace: true to solve this problem, but that's been deprecated and isn't even available for .component.
As you mention, it is not directly possible as you describe. An attributes property would be usefull, but does not exist as of yet.
A possible work-around would be to use $element inside your controller. This passes a jQuery element as a dependency, so you can add attributes as needed.
angular
.module('myComponent', [])
.component('myComponent', {
bindings: {
greeting: '<'
},
controller: function($element) {
$element.addClass('hello-world');
$element.attr('aria-hidden', true);
$element.data('my-greeting', this.greeting);
},
template: 'Define your template here.'
});
The <myComponent> element would now have a hello-world class and a aria-hidden attribute. It is even possible to use bindings, as described above with greeting.
The angular component definition is just a wrapper around normal directives.
I am picking up Angular for a project of mine and am having trouble getting my first steps right.
Specifically, I can get a list of items to display via a component and appropriate template, but I can not figure out how to trigger ng-click events using the component model. Many similar problems to this have been answered on SO but I have followed the many corrections and suggestions without progress and need some advice.
file: customerList.js
function CustomerListController($scope, $element, $attrs, $http) {
this.customerList = [
{ name: 'Arya' },
{ name: 'No One' },
];
this.yell = function(customer) {
console.log("customer customer, we've got a click");
};
}
angular.module('myApp').component('customerList', {
templateUrl: 'customerList.html',
controller: CustomerListController,
});
And its template:
file: customerList.html
<div class="customer"
ng-repeat="customer in $ctrl.customerList"
customer="customer"
ng-click="$ctrl.yell(customer);">
Welcome home, {{customer.name}}!
</div>
Even when I set ng-click="console.log('click detected');", I get no console log.
I believe this is sufficient information to diagnose but please let me know if you need more.
Thanks!
First of all, console.log will not work directly in an angular expression. You can't use window functions directly in expressions.
Second, I would recommend using controllerAs syntax as it's a newer school way of doing things. Try accessing the controller with your controllerAs alias in the ng-click() expression.
I am trying to find a way to dynamically construct a template in Angular2. I was thinking templateRef might provide a way to do this. But I could be wrong.
I found an example of templateRef being used here.
I was looking at templateRef in this example. I noticed the syntax is [ng-for-template] I also tried [ngForTemplate] cause I know this has changed recently.
So at the moment I have this:
import {Component, TemplateRef} from 'angular2/core';
#Component({
selector : 'body',
template : `
<template [ngForTemplate]="container">
<div class="container"></div>
</template>
`
})
export class App
{
#ContentChild(TemplateRef) container;
constructor() {}
ngAfterContentInit()
{
console.log(this);
}
}
This example throws an error:
Can't bind to 'ngForTemplate' since it isn't a known native property
So firstly I am wondering. What is the right way to do this? The docs don't provide any examples.
Secondly, is there a good way I can add new template logic to my template or dynamically construct a template? The structure of the application can be a very large amount of different structural combinations. So if possible I would like to see if there is a way I can do this without having a huge template with a bunch of different ngIf and ngSwitch statements..
My question is really the first part about templateRef. But any help or suggestions on the second part is appreciated.
Creating your own template directive it's not difficult, you have to understand two main things
TemplateRef contains what's inside your <template> tag
ViewContainerRef as commented by Gunter, holds the template's view and will let you to embed what's inside the template into the view itself.
I will use an example I have when I tried to solve this issue, my approach is not the best for that, but it will work for explaining how it works.
I want to clarify too that you can use any attribute for your templates, even if they're already used by builtin directives (obviously this is not a good idea, but you can do it).
Consider my approach for ngIfIn (my poor approach)
<template [ngIfValue]="'make'" [ngIfIn]="obj">
This will print
</template>
<template [ngIfValue]="'notExistingValue'" [ngIfIn]="obj">
This won't print
</template>
We have here two templates using two inputs each ngIfIn and ngIfValue, so I need my directive to grab the template by these two inputs and get their values too, so it would look like this
#Directive({
selector : '[ngIfIn][ngIfValue]',
inputs : ['ngIfIn', 'ngIfValue']
})
First I need to inject the two classes I mentioned above
constructor(private _vr: ViewContainerRef, private _tr: TemplateRef) {}
I also need to cache the values I'm passing through the inputs
_value: any;
_obj: any;
// Value passed through <template [ngIfValue]="'...'">
set ngIfValue(value: any) {
this._value = value;
}
// Value passed through <template [ngIfIn]="...">
set ngIfIn(obj: any) {
this._obj = obj;
}
In my case I depend on these two values, I could have my logic in ngOnInit but that would run once and wouldn't listen for changes in any of the inputs, so I put the logic in ngOnChanges. Remember that ngOnChanges is called right after the data-bound properties have been checked and before view and content children are checked if at least one of them has changed (copy and paste from the docs).
Now I basically copy & paste NgIf logic (not so complex, but similar)
// ngOnChanges so this gets re-evaluated when one of the inputs change its value
ngOnChanges(changes) {
if(this._value in this._obj) {
// If the condition is true, we embed our template content (TemplateRef) into the view
this._vr.createEmbeddedView(this._tr);
} else {
// If the condition is false we remove the content of the view
this._vr.clear();
}
}
As you see it's not that complicated : Grab a TemplateRef, grab a ViewContainerRef, do some logic and embed the TemplateRef in the view using ViewContainerRef.
Hopefully I made myself clear and I made how to use them clear enough also. Here's a plnkr with the example I explained.
ngForTemplate is only supported with ngFor
<template [ngFor] [ngForOf]="..." [ngForTemplate]="container"
or
<div *ngFor="..." [ngForTemplate]="container"
not on a plain template. It is an #Input() on the NgFor directive
Another way to use TemplateRef
If you have a reference to ViewContainerRef you can use it to "stamp" the template
constructor(private _viewContainer: ViewContainerRef) { }
ngOnInit() {
this.childView = this._viewContainer.createEmbeddedView(this.templ);
this.childView.setLocal('data', this.data);
}
I'm using ui.grid to get a list of parts. I've created a column that contains a button which launches a modal. What I'm having trouble with is sharing the scope of the part that is contained in the row. I want to share the properties of that row with the the button that I'm creating using cellTemplate. I then want to share the $scope of the part row with the modal that it will launch.
I'm a bit stumped on how to actually do this.
So far I've tried
• Wrapping an ng-repeat around the button that I want to target. This kind of works but makes the app super slow
• Data-binding on the button via ng-class. I can't seem to target this correctly.
How can you share the $scope of an object that you're receiving via $http.get into the ui.grid with elements that you're creating with cellTemplate?
Disclaimer -- I always use controllerAs syntax, so if referencing the controller in the context of HTML is weird to you, just ignore that part and pretend like you setup the methods to be directly on the scope. I also do everything in Typescript, not Javascript, so I'm going to write the pertinent parts of the code in here. They should be easy to plug into your application.
The answer is a combination of the two answers you already have from Sunil and S.Baggy.
What you want to do is use the getExternalScopes() function and attach something to the scope of the HTML where your grid resides. The thing you handed the grid will take in the row and call your modal popup. See below for a little clarification.
Your HTML -
<div ng-controller="MyController as myController">
<div ui-grid="myController.GridObject" external-scopes="myController"></div>
</div>
By using controllerAs syntax and making the controller the reference in the external scopes, we can now gain access to everything in our controller. So we can call methods in it.. In order to do that, however, we have to use a cellTemplate, which it sounds like you already know how to do, and in that cellTemplate we have to have the following:
ng-click="getExternalScopes().methodToLaunchModal()"
Now the last part of hooking all this up is to write the methodToLaunchModal() method into the controller. For that we're borrowing the code from S.Baggy's answer. Here is a very abbreviated controller with the GridObject (the same one I referenced from the controller above):
app.controller('MainCtrl', function($scope, $modal) {
GridObject = {
... setup of all the other things
columnDefs: [{ etc, etc, }, { etc, cellTemplate: '<div ng-click="getExternalScopes().methodToLaunchModal(row.entity)">whatever</div>' }]
};
methodToLaunchModal: function(row) {
var modalInstance = $modal.open({
templateUrl: 'someTemplate',
controller: 'ModalController',
resolve: {
rowObject: function () { return row; }
}
});
};
});
At this point your modal scope will have an object named rowObject on it that will have all the properties from your row. So you should be able to call rowObject.SomeProperty to get its value.
Apologies if any of the syntax is slightly off.
I use the bootstrap $modal directive with code like this...
clickFunction: function (event, row) {
event.stopPropagation(); // prevents the current row from appearing as selected
var modalInstance = $modal.open({
templateUrl: 'views/modalcontent.tpl.html',
controller: 'ModalMessageController',
size: 'lg',
resolve: {
message: function () { return row.entity.serial_number; }
}
}
);
Then I just refer to {{message}} in the template. Of course you could pass in any other piece of data too.
You can access row and its properties on row selection or ng-click of that row using externalscopes
ng-click="getExternalScopes().onRowClick(row)"
onRowClick: function (row) {
row.entity.Property1; /// and so on for all row properties
}