Background
In angular 1.3 'You can no longer invoke .bind, .call or .apply on a function in angular expressions.'.
In angular 1.2 I was using methods on a controller/directive's scope to generate text / templates for objects in a mixed collection.
Example of the Problem
For example, this example controller contains an array containing objects of varying (non-uniform) types and structures:
app.controller('flavourText', function ($scope) {
$scope.exampleData = {
data: [
{dataType: 'a', message: 'Type A String'},
{dataType: 'b', numbers: [1,2,3,]},
{dataType: 'a', message: 'Another Type A String'},
{dataType: 'b', numbers: [1,3,3,7]},
{dataType: 'a', message: 'Last Type A String'}
]
};
);
Approaches
I figured out two ways to generate flavour text / switch templates:
Method 1: Using ng-if
<!-- FIRST WAY OF DOING THINGS -->
<ul>
<li ng-repeat="item in $scope.example.data">
<span ng-if="item.dataType === 'a'">This is an example of type A: {{item.message}} </span>
<span ng-if="item.dataType === 'b'">This is an example of type B: {{item.numbers}} </span>
</li>
</ul>
This method gets really messy/inefficient in the HTML, so I started using a second method.
Method 2: Using functions in expressions
In the controller:
$scope.generateFlavourText = function (item){
if (item.dataType === 'a') {
return "This is an example of type A: " + item.message;
} else if (item.dataType === 'b'){
return "This is an example of type B: " + item.numbers;
}
};
In the template:
<!-- FOLLOWING METHOD DOES NOT WORK IN ANGULAR 1.3 -->
<ul>
<li ng-repeat="item in $scope.example.data">
{{generateFlavourText(item)}}
</li>
</ul>
The Questions
Directive Formatters/Parsers
Am I supposed to be using directives and ngModel formatters/parsers for this?
Is there a better way?
Should I just give in and just revert back to method 1, which gets really messy and confusing (+ expensive unless bindonce is used).
$scope.example.data. – PSL Dec 18 '14 at 22:10{{generateFlavourText(item)}}is an expression containing a function – Rai Butera Dec 18 '14 at 22:32$scope.generateFlavourText(item)You can have any expression in the interpolation. I did not understand what you meant by not working in 1.3. It just works if you remove$scopefrom ng-repeat – PSL Dec 18 '14 at 22:32.bind, .call or .applybecause they can change the context.. It does not mean that you cannot dogenerateFlavourText(item), but it means you cannot dogenerateFlavourText.bind($parent, item)()orgenerateFlavourText.call(this, item)– PSL Dec 18 '14 at 22:42