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

Deadly 提交于 2019-12-10 14:33:01

问题


In my Angular project, I am using a particular value that in my controller is called something like:

$scope.feature1.items.thisItem

There's a particular <div> in my view that uses thisItem many times and it's quite messy to be referring 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>

Is there any way to rename this variable in the view? I would like to simply call it one. I've tried {{feature1.items.thisItem as one}} but that didn't work. Any other ideas?


回答1:


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

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



回答2:


I would advise against using ng-init, it's not designed for this purpose. From Angular's 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.

You'll want to create a custom controller for this purpose. Something like the following:

module.controller('RenameController', function($scope) {

  $scope.one = null;

  $scope.$watch('feature1.items.thisItem', function(value) {
    $scope.one = value;
  });

});



回答3:


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

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


来源:https://stackoverflow.com/questions/27520797/is-there-a-way-to-rename-an-angular-variable-in-the-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!