質問

I'm dynamically building a form with angular depending of the kind of input:

<div ng-controller="formController" ng-repeat="field in formFields" ng-switch="field.type">
    <div ng-switch-when="text">
        <!-- Something -->
    </div>

    <div ng-switch-when="dropdown">
        <myDirective my-data="field.param" ng-model="field.model"></myDirective>
    </div>
</div>

I've got two problems with my directive which builds a custom dropdown input:

  1. Ng-model directive interprated the name field.model as plain text, whereas I would like the attributs ng-model="field.model" would be replaced by the value contained into field.model. Curly brackets don't seems to work here. Any idea?

  2. How to let the ng-model value accessible both in my form controller, and into my custom directive's controller?

Exemple of a field object:

{
    label : "Name",
    model : "employeeName",
    type : "dropdown",
    param : {
        dropdownArray : result,
        dropdownName : 'Nom',
        dropdownFieldValue : 'nameUUID',
        dropdownVisibleValue : [ 'employeeSS', 'employeeName' ]
    }    
}

Then in my controller I should be able to access this dropdown value with: $scope.employeeName.

役に立ちましたか?

解決

  1. It sounds like you're accessing field.model via the attributes input parameter supplied to the link function in your directive. Instead, you should be accessing it via the scope variable.

    link: function(scope, element, attributes) {
      // attributes.ngModel will yield 'field.model'
      // scope.ngModel will contain the actual value of field.model
    }
    
  2. If you don't explicitly define an isolate scope for your directive, then ng-model assigned to field.model should be available in your directive via the scope variable as I mentioned above.

    scope: false  // This is the default
    
    // Define an isolate scope with field.model available through scope.ngModel
    scope: {
      ngModel: '='
    }
    

Hope that helps.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top