大家好我正在尝试学习Angular,我希望从Span获取数据并追加另一个span。请帮帮我。 我的代码在这里
<div ng-app="" >
<div>
Name: <span ng-init="firstName='Ritu'">Ritu</span>
Address: <span ng-init="address='Uttam Nagar'">Uttam Nagar</span>
City: <span ng-init="city='West Delhi'">West Delhi</span>
State: <span ng-init="state='Delhi'">Delhi</span>
pin: <span ng-init="pin='110045'">110045</span>
<button>Click and Show</button>
</div
我希望在点击“显示”按钮
后显示<p>Name <span ng-bind="firstName"></span></p>
<p>Address <span ng-bind="address"></span></p>
<p>City <span ng-bind="city"></span></p>
<p>State <span ng-bind="state"></span></p>
<p>pin <span ng-bind="pin"></span></p>
</div>
提前致谢。
答案 0 :(得分:0)
我创建了一个可以做你想做的事情的plnkr。看看http://plnkr.co/edit/8xZik28CECenuPpLgdpq?p=preview 我使用 ng-show 指令,结果为 css显示(阻止或无)如果您愿意,可以使用 ng-if 但 ng-if 在使用了很多次后会产生性能影响,您可以找到其他方法,我只是想快速移动。
html部分
<body ng-controller="MainCtrl">
Name: <span ng-init="firstName='Ritu'">Ritu</span>
Address: <span ng-init="address='Uttam Nagar'">Uttam Nagar</span>
City: <span ng-init="city='West Delhi'">West Delhi</span>
State: <span ng-init="state='Delhi'">Delhi</span>
pin: <span ng-init="pin='110045'">110045</span>
<button data-ng-click="show=!show">Click and Show</button>
<div ng-show="show">
<p>Name <span ng-bind="firstName"></span></p>
<p>Address <span ng-bind="address"></span></p>
<p>City <span ng-bind="city"></span></p>
<p>State <span ng-bind="state"></span></p>
<p>pin <span ng-bind="pin"></span></p>
</div>
</body>
app.js
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.show=false;
});
答案 1 :(得分:0)
首先,许多使用ng-init
指令通常不是最佳实践。 Take a look angular's advice。
因此,我认为初始化值必须放在控制器中。
请查看此plunker。
答案 2 :(得分:0)
ng-init 用于获取初始数据,但它也会在模板中获得不必要的逻辑 您可以在Controller中执行相同的初始化,如:
app.controller('MainCtrl', function($scope) {
$scope.user = {
firstName: 'Ritu',
address: 'Uttam Nagar',
city: 'West Delhi',
state: 'Delhi',
pin: '110045'
}
$scope.show=false; });
并在视图中绑定用户对象,如:
<body ng-controller="MainCtrl">
Name: <span>{{user.firstName}}</span>
Address: <span>{{user.address}}</span>
City: <span>{{user.city}}</span>
State: <span>{{user.state}}</span>
pin: <span>{{user.pin}}</span>
<button data-ng-click="show=!show">Click and Show</button>
<div ng-show="show">
<p>Name <span ng-bind="user.firstName"></span></p>
<p>Address <span ng-bind="user.address"></span></p>
<p>City <span ng-bind="user.city"></span></p>
<p>State <span ng-bind="user.state"></span></p>
<p>pin <span ng-bind="user.pin"></span></p>
</div>
</body>
这简化了代码并使模板保持干净 Here is a plunker