I created a directive on Angular that receives 5 parameters and one of them is an optional array. The way I'm trying to deal with it is like follows:
app.directive('fooDirective', function() {
return {
restrict: 'AE',
scope: {
param1: '=',
param2: '=' // optional array
},
template: //...
"<div ng-class='defineClass()'> Message </div>"
//...
controller: function($scope) {
if (typeof $scope.param2 === 'undefined')
$scope.param2 = [];
console.log($scope.param2);
$scope.defineClass = function() {
if ($scope.param2.length == 0) return 'gray-text';
return 'red-text';
};
// ......
}
}
});
At some point in my code I check for the .length of param2 and if it is undefined it throws a lot of errors. What is driving me nuts is that the console.log() you can see there outputs a [], indicating that the .length of my param should be 0 and the errors on the console are shown after the output of the console.log().
So I guess I am missing something about either the way Angular binds the scopes or the flow that the directive is constructed. I have tried verifing my param on both link and compile phases and got the same problem.
So, what am I missing here? Thanks in advance.
From the angular documentation (see the section for scope bi-directional binding):
= or =attr - set up bi-directional binding between a local scope property and the parent scope property of name defined via the value of the attr attribute....
If the parent scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You can avoid this behavior using =? or =?attr in order to flag the property as optional.
So the solution to make the parameter optional is to change the binding to be an optional two-way binding with the additional ?.
...
scope: {
param1: '=',
param2: '=?' // notice the ? makes this parameter optional.
},
...
Related
I've created a simplest possible directive with bindToController syntax, which resulted in a crysis of faith due to what I've seen:
function foobar() {
return {
restrict: 'E',
scope: {
foo: '='
},
template: "<div>foo = {{ vm.foo }}</div>",
bindToController: true,
controllerAs: "vm",
controller: ["$scope", function($scope) {
console.log(this); // print controller
console.log(this.foo); // print controller attribute
}]
};
}
Now, in html I say:
<foobar foo="1"></foobar>
and in the resulting html I see my div's content as expected:
foo = 1
But in the console I see:
controller
foo: 1
__proto__: Object
undefined
Ugh, what? So, somehow, foo is seen as an attribute of controller, but it is not available as this.foo like ordinary object properties. How do I access and modify it then? And what's going on with those 2-way binded data?
JSBin: https://jsbin.com/xidepewofe/edit?html,js,output
2-way binding expect variable not value, should be:
<div ng-init="myvarname = 1">
<foobar foo="myvarname"></foobar>
</div>
Another option is to change binding type to '#'.
In 1.6 change was introduced - by default bindings got resolved not immediately but before $onInit. So wrap your code in $onInit:
var vm = this;
vm.$onInit = function() {
console.log(vm.foo);
}
or change setting:
.config(function($compileProvider){
$compileProvider.preAssignBindingsEnabled(true)
});
How can I pass in the value of an Angular expression to a component's attribute? I'm getting the value back from an API.
app.controller.js
$http.get(apiUrl).then(function(resp) {
$scope.name = resp.data.name;
})
...
person.component.js
export const Person = {
templateUrl: 'person.html',
bindings: {
firstName: '#'
},
controller: function() {
console.log(this.firstName);
}
}
app.html
...
<person first-name="name">
For some reason it's not evaluating name and it's logging undefined in the console.
Is there a way around this so it logs Tom inside the controller?
Any help is appreciated. Thanks in advance!
I've setup a jsFiddle here
& is for expressions, and # is for interpolated strings, so try using
firstName: '&'
and then this.firstName() should evaluate the expression passed in.
Also, firstName is not guaranteed to have been initialized until $onInit, so if you do
bindings: {
firstName: '&'
},
controller: function() {
this.$onInit = function() {
console.log(this.firstName());
}
}
you should get your expected result.
For reference: https://docs.angularjs.org/guide/component
$onInit() - Called on each controller after all the controllers on an element have been constructed and had their bindings initialized
Edit:
After the extra information you provided, you should probably use a one-way binding (<) instead for this case, because it appears you are just passing in a single value (instead of an expression), and then you can detect changes in $onChanges. I forked your jsfiddle to show a potential solution: http://jsfiddle.net/35xzeo94/.
I'm refactoring some angular directives to angular 1.5-style components.
Some of my directives have behavior that depends on a certain attribute being present, so without the attribute having a specific boolean value. With my directives, I accomplish this using the link function:
link: function(scope,elem,attrs, controller){
controller.sortable = attrs.hasOwnProperty('sortable');
},
How would I do this with the angular 1.5-style component syntax?
One thing I could do is add a binding, but then I'd need to specify the boolean value. I'd like to keep my templates as-is.
Use bindings instead of the direct reference to the DOM attribute:
angular.module('example').component('exampleComponent', {
bindings: {
sortable: '<'
},
controller: function() {
var vm = this;
var isSortable = vm.sortable;
},
templateUrl: 'your-template.html'
});
Template:
<example-component sortable="true"></example-component>
Using a one-way-binding (indicated by the '<') the value of the variable 'sortable' on the controller instance (named vm for view model here) will be a boolean true if set as shown in the example. If your sortable attribute currently contains a string in your template an '#' binding may be a suitable choice as well. The value of vm.sortable would be a string (or undefined if the attribute is not defined on the component markup) in that case as well.
Checking for the mere presence of the sortable attribute works like this:
bindings: { sortable: '#' }
// within the controller:
var isSortable = vm.sortable !== undefined;
Using bindings may work but not if you are trying to check for the existence of an attribute without value. If you don't care about the value you can just check for it's existence injecting the $element on the controller.
angular
.module('yourModule')
.component('yourComponent', {
templateUrl: 'your-component.component.html',
controller: yourComponentsController
});
function yourComponentController($element) {
var sortable = $element[0].hasAttribute("sortable");
}
There is a built-in way to do this by injecting $attrs into the controller.
JS
function MyComponentController($attrs) {
this.$onInit = function $onInit() {
this.sortable = !!$attrs.$attr.hasOwnProperty("sortable");
}
}
angular
.module("myApp", [])
.component("myComponent", {
controller: [
"$attrs",
MyComponentController
],
template: "Sortable is {{ ::$ctrl.sortable }}"
});
HTML
<my-component sortable>
</my-component>
<my-component>
</my-component>
Example
JSFiddle
So basically I have a controller, which lists a bunch of items.
Each item is rendering a directive.
Each directive has the ability to make a selection.
What I want to achieve is once the selection has been made, I want to call a method on the controller to pass in the selection.
What I have so far is along the lines of...
app.directive('searchFilterLookup', ['SearchFilterService', function (SearchFilterService) {
return {
restrict: 'A',
templateUrl: '/Areas/Library/Content/js/views/search-filter-lookup.html',
replace: true,
scope: {
model: '=',
setCriteria: '&'
},
controller: function($scope) {
$scope.showOptions = false;
$scope.selection = [];
$scope.options = [];
$scope.selectOption = function(option) {
$scope.selection.push(option);
$scope.setCriteria(option);
};
}
};
}]);
The directive is used like this:
<div search-filter-lookup model="customField" criteria="updateCriteria(criteria)"></div>
Then the controller has a function defined:
$scope.updateCriteria = function(criteria) {
console.log("Weeeee");
console.log(criteria);
};
The function gets called fine. But I'm unable to pass data to it :(
Try this:
$scope.setCriteria({criteria: option});
When you declare an isolated scope "&" property, angular parses the expression to a function that would be evaluated against the parent scope.
when invoking this function you can pass a locals object which extends the parent scope.
It's a common mistake to think that $scope.setCriteria is the same as the function inside the attribute. If you log it you'll see it's just an angular parsed expression function which have the parent scope saved at it's closure.
So when you run $scope.setCriteria() you actually evaluate an expression against the parent scope.
In your case this expression happens to be a function but it could be any expression.
But you don't have a criteria property on the parent scope, that's why angular let you pass a locals object to extend the parent scope. e.g. {criteria: option}
Extends the parent scope
you wrote in a comment that it requires the directive to have knowledge of the parameter name defined in the controller. No it doesn't, it just extends the parent scope with a criteria option, you can still use any expression you want though you are provided with an extra property you may use.
A good example would be ngEvents, take ng-click="doSomething($event)":
ngClick provides you with a local property $event, you don't have to use but you may if you need.
the directive doesn't know anything about the controller, it's up to you to decide which expression you write, cheers.
You can pass the function in using =...
scope: {
model: '=',
setCriteria: '='
},
controller: function($scope) {
// ...
$scope.selectOption = function(option) {
$scope.selection.push(option);
$scope.setCriteria(option);
};
}
<div search-filter-lookup model="customField" criteria="updateCriteria"></div>
I have a custom directive. In my html i write this:
<uploader action="/rest/file/create_from_form.json" success="writeFid()"></uploader>
What I need is to exec "success" attribute function passing some data that I get from my directive. I can exec "success" attribute function via
$scope.$eval($scope.success)
and in my "controller" I have this:
$scope.writeFid = function (data) {
console.log("Into writeFid");
console.log(data); //this is my problem: it is always undefined.
}
I can see (via console.log() messages) that "success" function is called but without passing "data".
I have tried to use
<uploader action="/rest/file/create_from_form.json" success="writeFid(data)"></uploader>
but it does not work.
So: how can i pass some type of $scope.data ?
Thanks.
I'm not sure whether your directive uses an isolate scope or not, so I'll cover both cases:
Without an isolate scope:
scope.$eval(attrs.success, { data: 'Some value from foo' });
With an isolate scope:
scope: { success: '&' },
...
scope.success({ data: 'Some value from bar' });
Regardless of the type of the scope, your markup must be like this:
<uploader success="writeFid(data)" ...></uploader>
And here's a plunk script showing both approaches.
You could use an isolate scope with a bi-directional binding in your uploader directive to somewhat achieve what you're after.
uploader directive
...
scope: {
data: '=',
success: '&'
}
...
Sample parent controller
app.controller('MainCtrl', function($scope) {
$scope.dataAttribFromParent = { data: [] };
$scope.writeFid = function () {
console.log($scope.dataAttribFromParent);
};
});
markup
...
<uploader data="dataAttribInParent" success="writeFid()">
...
Here's a plunk to elaborate:
http://plnkr.co/edit/7Kzy6D7cwxlATEBKRcuT