2015-02-17 94 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); 
    }; 
}