Reputation: 11069
It seems to be a simple question but after a few month working with angular I'm still looking for a clean way to do it.
My template myTimePicker.html is defined in a directive so I got
<myTimePicker></myTimePicker>
Inside my template I have a "pickedTime" object
I need to pickup 3 different times and I dont' want to write 3 templates for the same code (obviously..). I would like to have it defined like a variable for a function, something like:
<myTimePicker ng-***="pickedTime1 as pickedTime" ></myTimePicker>
<myTimePicker ng-***="pickedTime2 as pickedTime" ></myTimePicker>
<myTimePicker ng-***="pickedTime3 as pickedTime" ></myTimePicker>
This works perfectly in ng-repeat when you write
ng-repeat="item in items"
You can use the same template for different items but each item has different variable values inside.
ng-init is not the solution because in this case:
<myTimePicker ng-init="pickedTime = pickedTime1"></myTimePicker>
<myTimePicker ng-init="pickedTime = pickedTime2"></myTimePicker>
...
pickedTime = pickedTime1 = pickedTime2 and they got all the same value pickedTime2
I hope it's clear, thank you for helping!
Upvotes: 1
Views: 3343
Reputation: 5270
<myTimePicker ng-init="pickedTime = pickedTime1"></myTimePicker>
<myTimePicker ng-init="pickedTime = pickedTime2"></myTimePicker>
...
ng-init doesn't work in above code is because model pickedTime
is modified twice and set as pickedTime2
at last.
If you use <myTimePicker ng-repeat="pickedTime in pickedTimes" ></myTimePicker>
, for each myTimePicker
element, ng-repeat
will create an isolated scope and bind a new pickedTime
to it, which can be accessed in your direcitve.
Upvotes: 0
Reputation: 37711
Use a custom attribute and use it combined with an isolate scope:
<myTimePicker pickedTime="pickedTime1"></myTimePicker>
<myTimePicker pickedTime="pickedTime2"></myTimePicker>
<myTimePicker pickedTime="pickedTime3"></myTimePicker>
scope: {
pickedTime: '='
}
This way you'd be able to inject the controller scope variables into the directive using the pickedTime
attribute.
Here's a simple example using strings instead of real times:
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: '='
}
}
});
<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>
Upvotes: 4