在模板中重用对象引用

Reuse Object Reference in a Template

我有这样的指令:

app.directive("myData", function() {
    return {
        restrict: "E",
        templateUrl: "myTemplate.html"
    };
});

然后在 myTemplate.html 我有类似的东西:

<input type="number"
       ng-if="(getMyObject(item.DataId)).Valid"
       ng-model="(getMyObject(item.DataId)).Price"/>

<div ng-bind="(getMyObject(item.DataId)).Price"
     ng-if="!(getMyObject(item.DataId).Valid"></div>

此指令位于 ng-repeat 中(因此是 item.)。

我的问题是如何将从 getMyObject() 获得的对象存储在某个地方,这样我就不必重复调用它?我尝试将 ng-init 用作:

<p ng-init="dataObject=getMyObject(item.DataId)"/>

并像这样引用它:

<input type="number"
       ng-if="dataObject.Valid"
       ng-model="dataObject.Price"/>

<div ng-bind="dataObject.Price"
     ng-if="!dataObject.Valid"></div>

但是一旦我提交任何更改并更改模型中的数据,这将不起作用,因为 ng-init 仅在页面加载时第一次起作用。

您可以在链接函数中设置一次性绑定:

app.directive("myData", function() {
  return {
      restrict: "E",
      templateUrl: "myTemplate.html",
      link: function(scope) {
        scope.dataObject = scope.getMyObject(scope.item.DataId);
      }
  };
});

这样,您的指令的每个实例都会有一个 dataObject,但只计算一次。现在,如果您需要 "recompute" 这个 dataObject 进行一些更改后,您可以在函数或观察者中执行此操作:

link: function(scope) {
  scope.dataObject = scope.getMyObject(scope.item.DataId);

  // Option 1
  scope.$watch('somethingToWatch', function() {
    scope.dataObject = scope.getMyObject(scope.item.DataId);
  });

  // Option 2 (choose one or the other)
  scope.onSubmit = function() {
    scope.dataObject = scope.getMyObject(scope.item.DataId);
  };
}