在我的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}}
但是没有用。还有其他想法吗?
答案 0 :(得分:7)
是的! ng-init是为此目的而设计的 - 别名另一个变量:
<div ng-init="thisItem = feature1.items.thisItem">
<h1> You've reached the section about {{thisItem}} </h1>
</div>
答案 1 :(得分:3)
我建议不要使用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;
});
});
答案 2 :(得分:2)
是的,您可以在DOM元素的顶部使用ng-init
<div ng-app='app'>
<div ng-controller="MyController" ng-init="myVar=feature1.items.thisItem">
{{myVar}}
</div>
</div>