[英]Give angular directive a model name to access it's scope in the parent
當我在HTML中使用它時,我試圖通過在它的元素上使用模型屬性來訪問指令的孤立范圍。 例如。
<div controller="parent">
<hello-world data-ng-model="hw"/>
<input type="submit"/>
</div>
父母的控制器:
function($scope){
$scope.submit = function(){
alert($scope.hw.t);
}
};
你好世界的指令:
app.directive('helloWorld', function() {
return {
link: function(scope, element, attrs){
scope.t = 'test';
},
replace: true,
restrict: 'E',
scope: {},
template: '<h5>Hello world {{t}}</h4>'
};
});
t在隔離范圍中定義,因為它顯示正確。 但是,當我單擊提交按鈕時,我收到錯誤,因為未定義hw。 (因為hello-world范圍沒有被分配給父級的'hw'范圍變量。我怎樣才能將hw定義為hello-world指令的范圍?我的用例是創建一個日期選擇器暴露通過它的范圍挑選的日期。喜歡
<date-picker ng-model="date1"/>
<date-picker ng-model="date2"/>
在指令范圍內,我將確保定義月份,年份等。 然后在父控制器中,我可以使用$scope.date1.month
和類似訪問選擇的日期。
在您的評論之后,您似乎需要使用ngModel制作自定義可驗證元素。
根據ngModel
的文檔 ,這可以通過使用手動ngModelController
來完成。 以下頁面應包含您需要的所有信息(請參閱示例中的script.js
): https : //docs.angularjs.org/api/ng/type/ngModel.NgModelController
祝好運。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.