[英]Isolate scope fallback in AngularJS
我正在嘗試為輸入框構建一個自定義指令,該輸入框具有input-model
作為用作ng-model的屬性。 此輸入模型屬性與內部范圍變量綁定有兩種方式。
templateUrl:'/components/directives/inputBox.html',
transclude:true,
restrict: 'A',
scope:{
userInput : '=inputModel'
}
現在的問題是,當我顯式提供輸入模型時,在主html中,它可以正常工作。 但是,當沒有提供輸入模型時,我要回退,然后應刪除兩種方式的綁定。 模板就像
<input id="searchinput" type="search"
name="inputBox"
class="form-control"
placeholder="{{placeholder}}"
ng-model="userInput"
ng-pattern="pattern">
因此,當我不在主要html中提供input-model
屬性時
<div input-box></div>
綁定失敗,出現錯誤:
Error: [$compile:nonassign] Expression 'undefined' used with directive 'inputBox' is non-assignable!
我想回退以避免這種情況。 我應該如何進行?
該解決方案對您有用嗎?
您可以在compile方法中檢查已定義的屬性,這將允許您在綁定發生之前處理這種情況。
return {
template: '<div>{{userInput}} - test</div>',
transclude: true,
restrict: 'A',
scope: {
userInput: '=inputModel'
},
compile: function(element, attrs, transclude) {
if (!attrs.inputModel) {
attrs.inputModel = 'userInput';
}
return {
pre: function(scope, element, attrs) {},
post: function(scope, element, attrs) {}
}
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.