【问题标题】:Is there a way to rename an Angular variable in the view?有没有办法在视图中重命名 Angular 变量?
【发布时间】:2015-02-15 17:14:33
【问题描述】:

在我的 Angular 项目中,我使用了一个特定的值,在我的控制器中被称为:

$scope.feature1.items.thisItem

在我看来,有一个特定的<div> 多次使用thisItem,例如将其称为{{feature1.items.thisItem}} 非常混乱:

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

有没有办法在视图中重命名这个变量?我想简单地称它为one。我试过{{feature1.items.thisItem as one}},但没用。还有其他想法吗?

【问题讨论】:

    标签: angularjs variables scope


    【解决方案1】:

    是的! ng-init 就是为此目的而设计的——给另一个变量起别名:

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

    【讨论】:

    • 可悲的是 ng-init 似乎已在 Angular 2+ 中被删除
    【解决方案2】:

    我建议不要使用 ng-init,它不是为此目的而设计的。来自Angular's documentation:

    ngInit 唯一合适的用途是为 ngRepeat 的特殊属性设置别名,如下面的演示所示。除了这种情况,您应该使用控制器而不是 ngInit 来初始化作用域上的值。

    您需要为此创建一个自定义控制器。类似于以下内容:

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

    【讨论】:

      【解决方案3】:

      是的,您可以在 DOM 元素的顶部使用 ng-init

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

      【讨论】:

        猜你喜欢
        • 2019-05-05
        • 2016-04-17
        • 1970-01-01
        • 1970-01-01
        • 2016-01-16
        • 1970-01-01
        • 2011-03-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多