2012-08-01 129 views
15

有誰知道如何使用AngularJS將插值插入到數據屬性中?AngularJS將值綁定到數據屬性

<input type="text" data-custom-id="{{ record.id }}" /> 

角度似乎沒有內插該值,因爲它的元素結構的一部分。任何想法如何解決這一問題?

+0

你能提供jsfiddle的例子嗎? – 2012-08-03 04:17:09

回答

6

看起來畢竟沒有問題。該模板被解析,我的控制器正在下載數據,但是當模板被解析時,數據還沒有出現。我放的指令需要數據在那裏同時它只是拾取空的宏數據。

,我解決了,這是與$ watch命令的方式:

$scope.$watch('ready', function() { 
    if($scope.ready == true) { 
    //now the data-id attribute works 
    } 
}); 

然後,當控制器已加載的所有Ajax的東西,那麼你這樣做:

$scope.ready = true; 
+0

selectOptions與您在問題中討論過的record.id有什麼關係? – Hengjie 2012-09-12 00:19:58

+0

我已更新代碼以使其更相關。 – matsko 2012-09-12 02:55:45

1

它看起來像我你是真的後,什麼是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); 
); 

編輯:正確的,這裏有一個簡單的考試用無極帶控制器和綁定的PLE:

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); 
    }; 
});​ 

工作的jsfiddle:http://jsfiddle.net/dain/QjnML/4/

基本上想法是,你可以綁定的承諾,一旦異步響應解決它,它將會實現。

+0

這太好了。但是,你能否提供一個更好地涉及我的問題的例子?我很難理解它。謝謝:) – matsko 2012-09-14 06:40:04

+0

它基本上是直接形式的文檔...這將是很好的給他一些與他的問題有關的東西。 – Nix 2013-05-06 14:58:19