2015-02-17 92 views
0

我有这样的指令:再用对象参考

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仅适用于第一次加载页面时。

+0

什么是getMyObject发生这样的,如果你反复调用它,它事项?如果你需要一个表达式来确定你绑定或在ng-if中使用什么。如果您多次拨打该功能,这有什么关系 – jw56578 2015-02-17 21:13:57

+0

对不起,我没有解释得很好。因为这个页面非常大,我嵌套了ng-repeat,所以我试图为了性能原因优化代码。 – notlkk 2015-02-17 21:33:52

回答

1

你可以设置一个时间,你的链接功能结合:

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

这样,你将有你的每指令instanciation一个dataObject,但只计算一次。现在,如果你需要一些改变后,“重新计算”这个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); 
    }; 
}