这似乎是一个简单的问题,但经过几个月的角度工作后,我仍然在寻找一种干净的方法。
我的模板myTimePicker.html是在一个指令中定义的,所以我得到了
<myTimePicker></myTimePicker>
在我的模板中,我有一个“pickedTime”对象
我需要拾取3次不同的时间,我不想为相同的代码编写3个模板(显然......)。我想将它定义为函数的变量,如:
<myTimePicker ng-***="pickedTime1 as pickedTime" ></myTimePicker>
<myTimePicker ng-***="pickedTime2 as pickedTime" ></myTimePicker>
<myTimePicker ng-***="pickedTime3 as pickedTime" ></myTimePicker>
当你写
时,这在ng-repeat中非常有效ng-repeat="item in items"
您可以对不同的项目使用相同的模板,但每个项目内部都有不同的变量值。
ng-init不是解决方案,因为在这种情况下:
<myTimePicker ng-init="pickedTime = pickedTime1"></myTimePicker>
<myTimePicker ng-init="pickedTime = pickedTime2"></myTimePicker>
...
pickedTime = pickedTime1 = pickedTime2,他们获得了相同的值pickedTime2
我希望它很清楚,谢谢你的帮助!
答案 0 :(得分:3)
使用自定义属性并将其与隔离范围结合使用:
<myTimePicker pickedTime="pickedTime1"></myTimePicker>
<myTimePicker pickedTime="pickedTime2"></myTimePicker>
<myTimePicker pickedTime="pickedTime3"></myTimePicker>
scope: {
pickedTime: '='
}
这样您就可以使用pickedTime
属性将控制器范围变量注入指令。
这是一个使用字符串而不是实时的简单示例:
angular.module('myApp', [])
.controller('Ctrl', ['$scope',
function($scope) {
$scope.pickedTime1 = 'First time';
$scope.pickedTime2 = 'Second time';
$scope.pickedTime3 = 'Third time';
}
])
.directive('myTimePicker', function() {
return {
template: '<p>{{pickedTime}}</p>',
restrict: 'E',
scope: {
pickedTime: '='
}
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="Ctrl">
<my-time-picker picked-time="pickedTime1">1</my-time-picker>
<my-time-picker picked-time="pickedTime2">2</my-time-picker>
<my-time-picker picked-time="pickedTime3">3</my-time-picker>
</div>
&#13;
答案 1 :(得分:0)
<myTimePicker ng-init="pickedTime = pickedTime1"></myTimePicker>
<myTimePicker ng-init="pickedTime = pickedTime2"></myTimePicker>
...
ng-init在上面的代码中不起作用是因为模型pickedTime
被修改了两次并且最后设置为pickedTime2
。
如果您使用<myTimePicker ng-repeat="pickedTime in pickedTimes" ></myTimePicker>
,则对于每个myTimePicker
元素,ng-repeat
将创建一个独立的范围并将新的pickedTime
绑定到该范围,可以在您的直接访问