Is there a way to rename an Angular variable in a view?

In my Angular project, I use a specific value, which in my controller is called something like:

$scope.feature1.items.thisItem

In my view, there is a specific <div> that uses thisItem many times, and rather randomly refer to it as {{feature1.items.thisItem}} , for example:

 <div id="{{feature1.items.thisItem}}header> <h1> You've reached the section about {{feature1.items.thisItem}} </h1> </div> 

Can I rename this variable in a view? I would just call it one . I tried {{feature1.items.thisItem as one}} but that did not work. Any other ideas?

+5
source share
3 answers

Yes! ng-init was designed for this purpose - smoothing another variable:

 <div ng-init="thisItem = feature1.items.thisItem"> <h1> You've reached the section about {{thisItem}} </h1> </div> 
+7
source

I would advise using ng-init, it was not intended for this purpose. From the Angular documentation :

The only suitable use of ngInit is to smooth out the special properties of ngRepeat, as shown in the demo below. Other than this case, you should use controllers instead of ngInit to initialize values ​​in the scope.

For this purpose, you will need to create a user controller. Something like the following:

 module.controller('RenameController', function($scope) { $scope.one = null; $scope.$watch('feature1.items.thisItem', function(value) { $scope.one = value; }); }); 
+3
source

Yes, you can use ng-init at the top of your DOM element

 <div ng-app='app'> <div ng-controller="MyController" ng-init="myVar=feature1.items.thisItem"> {{myVar}} </div> </div> 
+2
source

Source: https://habr.com/ru/post/1209310/


All Articles