Noah
Noah

Reputation: 4751

Change name of variable like in ng-repeat but without repeating?

In my app I have, say $scope.item. In my page I have templates that refer to that as something else, say $scope.product.

On one page I need to refer to the model as item, but then use ng-include to open templates that refer to it as product.

When I had just one item in an array, I did ng-repeat="product in item". Now I done away with the single array with an object and it's just an object. If I do ng-repeat it will repeat for each key/value pair in the object. Not what I want.

Is there a way to say ng-alias="item as product" or something?

Upvotes: 0

Views: 76

Answers (2)

floribon
floribon

Reputation: 19193

If it's a one-time binding you could do

<... ng-init="product = item" ...>

However from what I understand you where hacking ng-repeat for aliasing purpose with no real need to repeat. In this case ng-init will still be a hack that can cause you trouble later on.

The proper way to do what you want is put your template into a directive, and link the product variable of your directive from the given item. i.e. the html would look like this:

<my-directive product="item"></my-directive>

Upvotes: 0

Michael Kang
Michael Kang

Reputation: 52867

ngInit was intended for aliasing.

ng-init="item = product"

According to the documentation

The only appropriate use of ngInit is for aliasing special properties of ngRepeat, as seen in the demo below. Besides this case, you should use controllers rather than ngInit to initialize values on a scope.

Upvotes: 1

Related Questions