Does anyone know how to bind an interpolated value into a data attribute using AngularJS?
<input type="text" data-custom-id="{{ record.id }}" />
Angular doesn't seem to interpolate that value since its apart of the structure of the element. Any ideas how to fix this?
Looks like there isn't a problem after all. The template is parsed and my controller was downloading the data, but when the template was being parsed data wasn't there yet. And the directive I put needs the data to be there os in the mean time its just picking up empty macro data.
The way that I solved this was with the $watch command:
$scope.$watch('ready', function() {
if($scope.ready == true) {
//now the data-id attribute works
}
});
Then when the controller has loaded all the ajax stuff then you do this:
$scope.ready = true;
It looks like to me what you are really after is a Promise / Deferred:
// for the purpose of this example let's assume that variables '$q' and 'scope' are
// available in the current lexical scope (they could have been injected or passed in).
function asyncGreet(name) {
var deferred = $q.defer();
setTimeout(function() {
// since this fn executes async in a future turn of the event loop, we need to wrap
// our code into an $apply call so that the model changes are properly observed.
scope.$apply(function() {
if (okToGreet(name)) {
deferred.resolve('Hello, ' + name + '!');
} else {
deferred.reject('Greeting ' + name + ' is not allowed.');
}
});
}, 1000);
return deferred.promise;
}
var promise = asyncGreet('Robin Hood');
promise.then(function(greeting) {
alert('Success: ' + greeting);
}, function(reason) {
alert('Failed: ' + reason);
);
Edit: right, here's a simple example of using a Promise with a Controller and binding:
var app = angular.module('myApp', []);
app.controller('MyCtrl', function($scope, $q) {
var deferredGreeting = $q.defer();
$scope.greeting = deferredGreeting.promise;
/**
* immediately resolves the greeting promise
*/
$scope.greet = function() {
deferredGreeting.resolve('Hello, welcome to the future!');
};
/**
* resolves the greeting promise with a new promise that will be fulfilled in 1 second
*/
$scope.greetInTheFuture = function() {
var d = $q.defer();
deferredGreeting.resolve(d.promise);
setTimeout(function() {
$scope.$apply(function() {
d.resolve('Hi! (delayed)');
});
}, 1000);
};
});
Working JSFiddle: http://jsfiddle.net/dain/QjnML/4/
Basically the idea is that you can bind the promise and it will be fulfilled once the async response resolves it.