15

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

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

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

4

2 回答 2

6

看起来毕竟没有问题。模板已解析,我的控制器正在下载数据,但是在解析模板时数据还不存在。我提出的指令需要数据在操作系统中,同时它只是拾取空的宏数据。

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

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

然后,当控制器加载了所有 ajax 内容时,您可以执行以下操作:

$scope.ready = true;
于 2012-08-03T17:21:31.143 回答
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/

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

于 2012-09-14T00:09:42.810 回答