2016-05-31 3 views
0
<custom-input-container> 
     <input ng-model="myModel1" /> 
</custom-input-container> 

<custom-input-container> 
     <select ng-model="myModel2" > 
     </select> 
</custom-input-container> 

Я хочу сделать что-то вроде этого (если это возможно, я хочу эту директиву, чтобы можно было использовать на другом модуле приложения, разделив его в «customInput.js»)смотреть ngModel в моей директиве

myApp.directive('customInputContainer',function(){ 
    return{ 
     restrict: 'E', 
     priority: 0, 
     link:function(scope,element,attr){ 
      scope.watch->//i want to watch the ngModel of 
      the thing inside <custom-input-container> 
      then do console.log('recipe was updated:'+thenewvalue); 
     } 
    } 
}); 
+0

Примечание: каждый входной контейнер имеет только один из входных/выбранных/текстовых полей на нем – anaval

+0

Знаете ли вы, что «transclude» и его последствия? – AranS

+0

печально нет ... я очень новичок в angularjs – anaval

ответ

0

Nevermind, я получил это работает, как этот

myApp.directive('customInputContainer',function(){ 
    return{ 
     restrict: 'E', 
     priority: 0, 
     link:function(scope,element,attr){ 
      var modelToWatch = element.find('input','select').attr('ng-model'); 
      scope.$watch(modelToWatch,function(newVal,oldVal){ 
        console.log('recipe updated:'+newVal); 
      }); 
     } 
    } 
}); 

Теперь единственная проблема remaning как сделать заказ ввод-контейнер инъекционного к другим проектам, не изменяя мой customInput.js

0

Чтобы просмотреть переменную ng-model внутри директивы элемента, добавьте атрибут с именем требуемой переменной.

<custom-input-container recipe='myModel1'> 
     <input ng-model="myModel1" /> 
    </custom-input-container> 
    <br /> 
    <custom-input-container recipe='myModel2'> 
     Select 
     <select ng-model="myModel2" 
       ng-options="name for name in [1,2,3]"> 
     </select> 
    </custom-input-container> 

Затем в директиве добавьте наблюдателя.

app.directive('customInputContainer',function(){ 
    return{ 
     restrict: 'E', 
     link:function(scope,element,attr){ 
      scope.$watch(attr.recipe, function(value) { 
       console.log('recipe was updated: ', value); 
      }) 
     } 
    } 
}); 

выше директива использует атрибут recipe определить переменную для просмотра.

DEMO on JSFiddle

Смежные вопросы