AngularJS将值绑定到数据属性中

时间:2012-08-01 16:07:33

标签: angularjs

有没有人知道如何使用AngularJS将插值值绑定到数据属性?

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

Angular似乎没有插入该值,因为它的元素结构是分开的。任何想法如何解决这个问题?

2 个答案:

答案 0 :(得分:6)

毕竟看起来没有问题。解析模板,我的控制器正在下载数据,但是当解析模板时,数据还没有。而我所提出的指令需要数据在同一时间才能获取空宏数据。

我解决这个问题的方法是使用$ watch命令:

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

然后当控制器加载了所有ajax的东西时,你就这样做了:

$scope.ready = true;

答案 1 :(得分: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);
);

编辑:对,这是一个使用带控制器和绑定的Promise的简单示例:

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/

基本上,我们的想法是你可以绑定承诺,一旦异步响应解决它就会实现它。