AngularJS-Tworzenie dyrektywy wykorzystującej model ng

Próbuję stworzyć dyrektywę, która utworzyłaby pole wejściowe z tym samym modelem ng, co element tworzący dyrektywę.

Oto co wymyśliłem do tej pory:

HTML

<!doctype html>
<html ng-app="plunker" >
<head>
  <meta charset="utf-8">
  <title>AngularJS Plunker</title>
  <link rel="stylesheet" href="style.css">
  <script>document.write("<base href=\"" + document.location + "\" />");</script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js"></script>
  <script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
  This scope value <input ng-model="name">
  <my-directive ng-model="name"></my-directive>
</body>
</html>

JavaScript

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.name = "Felipe";
});

app.directive('myDirective', function($compile) {
  return {
    restrict: 'E',
    scope: {
      ngModel: '='
    },
    template: '<div class="some"><label for="{{id}}">{{label}}</label>' +
      '<input id="{{id}}" ng-model="value"></div>',
    replace: true,
    require: 'ngModel',
    link: function($scope, elem, attr, ctrl) {
      $scope.label = attr.ngModel;
      $scope.id = attr.ngModel;
      console.debug(attr.ngModel);
      console.debug($scope.$parent.$eval(attr.ngModel));
      var textField = $('input', elem).
        attr('ng-model', attr.ngModel).
        val($scope.$parent.$eval(attr.ngModel));

      $compile(textField)($scope.$parent);
    }
  };
});

Jednak nie jestem pewien, czy jest to właściwy sposób obsługi tego scenariusza, i jest błąd, że moja kontrola nie jest inicjalizowana z wartością pola docelowego modelu ng.

Oto Plunker kodu powyżej: http://plnkr.co/edit/IvrDbJ

Jaki jest prawidłowy sposób radzenia sobie z tym?

EDIT : po usunięciu ng-model="value" z szablonu wydaje się to działać poprawnie. Pozostanę jednak otwarty na to pytanie, ponieważ chcę dokładnie sprawdzić, czy jest to właściwy sposób działania.

Author: TimPetricola, 2013-01-02

8 answers

To całkiem niezła logika, ale można trochę uprościć.

Dyrektywa

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.model = { name: 'World' };
  $scope.name = "Felipe";
});

app.directive('myDirective', function($compile) {
  return {
    restrict: 'AE', //attribute or element
    scope: {
      myDirectiveVar: '=',
     //bindAttr: '='
    },
    template: '<div class="some">' +
      '<input ng-model="myDirectiveVar"></div>',
    replace: true,
    //require: 'ngModel',
    link: function($scope, elem, attr, ctrl) {
      console.debug($scope);
      //var textField = $('input', elem).attr('ng-model', 'myDirectiveVar');
      // $compile(textField)($scope.$parent);
    }
  };
});

Html z dyrektywą

<body ng-controller="MainCtrl">
  This scope value <input ng-model="name">
  <my-directive my-directive-var="name"></my-directive>
</body>

CSS

.some {
  border: 1px solid #cacaca;
  padding: 10px;
}

Możesz zobaczyć go w akcji za pomocą tego Plunkera.

Oto co widzę:

  • rozumiem, dlaczego chcesz używać 'ng-model', ale w Twoim przypadku nie jest to konieczne. ng-model polega na połączeniu istniejących elementów html z wartością w zakresie. Skoro sam tworzysz dyrektywę, to tworzenie' nowego ' elementu html, więc nie potrzebujesz ng-model.

EDIT jak wspomniał Mark w komentarzu, nie ma powodu, aby nie można używać ng-model, tylko po to, aby trzymać się konwencji.

  • poprzez jawne utworzenie zakresu w Twojej dyrektywie ('izolowany' zakres), zakres dyrektywy nie może uzyskać dostępu do zmiennej 'name' w zakresie nadrzędnym (dlatego, jak sądzę, chciałeś użyć ng-model).
  • usunąłem ngModel z Twojej dyrektywy i zastąpiono go niestandardową nazwą, którą można zmienić na cokolwiek.
  • to, co sprawia, że wszystko nadal działa, to znak ' = 'w zakresie. Sprawdź dokumenty dokumenty w nagłówku "zakres".

Ogólnie rzecz biorąc, twoje dyrektywy powinny używać izolowanego zakresu (co zrobiłeś poprawnie) i używać zakresu typu'=', jeśli chcesz, aby wartość w Twojej dyrektywie była zawsze mapowana do wartości w zakresie nadrzędnym.

 204
Author: Roy Truelove,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-02-15 19:17:37

Wzięłam kombinację wszystkich odpowiedzi, a teraz mam dwa sposoby na zrobienie tego z atrybutem ng-model:

  • z nowym zakresem kopiującym ngModel
  • z tym samym zakresem, który wykonuje kompilację na linku

var app = angular.module('model', []);

app.controller('MainCtrl', function($scope) {
  $scope.name = "Felipe";
  $scope.label = "The Label";
});

app.directive('myDirectiveWithScope', function() {
  return {
    restrict: 'E',
    scope: {
      ngModel: '=',
    },
    // Notice how label isn't copied
    template: '<div class="some"><label>{{label}}: <input ng-model="ngModel"></label></div>',
    replace: true
  };
});
app.directive('myDirectiveWithChildScope', function($compile) {
  return {
    restrict: 'E',
    scope: true,
    // Notice how label is visible in the scope
    template: '<div class="some"><label>{{label}}: <input></label></div>',
    replace: true,
    link: function ($scope, element) {
      // element will be the div which gets the ng-model on the original directive
      var model = element.attr('ng-model');
      $('input',element).attr('ng-model', model);
      return $compile(element)($scope);
    }
  };
});
app.directive('myDirectiveWithoutScope', function($compile) {
  return {
    restrict: 'E',
    template: '<div class="some"><label>{{$parent.label}}: <input></label></div>',
    replace: true,
    link: function ($scope, element) {
      // element will be the div which gets the ng-model on the original directive
      var model = element.attr('ng-model');
      return $compile($('input',element).attr('ng-model', model))($scope);
    }
  };
});
app.directive('myReplacedDirectiveIsolate', function($compile) {
  return {
    restrict: 'E',
    scope: {},
    template: '<input class="some">',
    replace: true
  };
});
app.directive('myReplacedDirectiveChild', function($compile) {
  return {
    restrict: 'E',
    scope: true,
    template: '<input class="some">',
    replace: true
  };
});
app.directive('myReplacedDirective', function($compile) {
  return {
    restrict: 'E',
    template: '<input class="some">',
    replace: true
  };
});
.some {
  border: 1px solid #cacaca;
  padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<div ng-app="model" ng-controller="MainCtrl">
  This scope value <input ng-model="name">, label: "{{label}}"
  <ul>
    <li>With new isolate scope (label from parent):
      <my-directive-with-scope ng-model="name"></my-directive-with-scope>
    </li>
    <li>With new child scope:
      <my-directive-with-child-scope ng-model="name"></my-directive-with-child-scope>
    </li>
    <li>Same scope:
      <my-directive-without-scope ng-model="name"></my-directive-without-scope>
    </li>
    <li>Replaced element, isolate scope:
      <my-replaced-directive-isolate ng-model="name"></my-replaced-directive-isolate>
    </li>
    <li>Replaced element, child scope:
      <my-replaced-directive-child ng-model="name"></my-replaced-directive-child>
    </li>
    <li>Replaced element, same scope:
      <my-replaced-directive ng-model="name"></my-replaced-directive>
    </li>
  </ul>
  <p>Try typing in the child scope ones, they copy the value into the child scope which breaks the link with the parent scope.
  <p>Also notice how removing jQuery makes it so only the new-isolate-scope version works.
  <p>Finally, note that the replace+isolate scope only works in AngularJS >=1.2.0
</div>

Nie jestem pewien, czy podoba mi się kompilacja w czasie link. Jeśli jednak tylko wymieniasz element na inny, nie musisz tego robić.

W sumie wolę pierwszą. Po prostu ustaw zakres na {ngModel:"="} i ustaw ng-model="ngModel" gdzie chcesz to w szablonie.

Update: wstawiłem fragment kodu i zaktualizowałem go dla Angular v1. 2. Okazuje się, że isolate scope jest nadal najlepszy, zwłaszcza, gdy nie używasz jQuery. Więc sprowadza się do:

  • Czy wymieniasz pojedynczy element: po prostu zamień go, zostaw zakres w spokoju, ale zauważ, że replace jest przestarzały dla wersji 2.0:

    app.directive('myReplacedDirective', function($compile) {
      return {
        restrict: 'E',
        template: '<input class="some">',
        replace: true
      };
    });
    
  • W przeciwnym razie użyj tego:

    app.directive('myDirectiveWithScope', function() {
      return {
        restrict: 'E',
        scope: {
          ngModel: '=',
        },
        template: '<div class="some"><input ng-model="ngModel"></div>'
      };
    });
    
 66
Author: w00t,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-19 14:34:29

To nie jest takie skomplikowane.: w dirctive użyj aliasu: scope:{alias:'=ngModel'}

.directive('dateselect', function () {
return {
    restrict: 'E',
    transclude: true,
    scope:{
        bindModel:'=ngModel'
    },
    template:'<input ng-model="bindModel"/>'
}

W Twoim html, Użyj jako normalne

<dateselect ng-model="birthday"></dateselect>
 50
Author: AiShiguang,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-25 05:40:41

Potrzebujesz ng-model tylko wtedy, gdy chcesz uzyskać dostęp do $viewValue lub $modelValue modelu. Zobacz NgModelController . I w takim przypadku użyłbyś require: '^ngModel'.

Resztę zobacz odpowiedź Roysa .

 29
Author: asgoth,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:10:43

To trochę spóźniona odpowiedź, ale znalazłem ten świetny post o NgModelController, który myślę, że jest dokładnie tym, czego szukasz.

TL; DR - możesz użyć require: 'ngModel', a następnie dodać NgModelController do funkcji linkowania:

link: function(scope, iElement, iAttrs, ngModelCtrl) {
  //TODO
}
W ten sposób nie są potrzebne żadne hacki - korzystasz z wbudowanych funkcji Angular ng-model
 15
Author: Yaniv Efraim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-28 15:40:08

Nie ustawiłbym ngmodel poprzez atrybut, można go określić bezpośrednio w szablonie:

template: '<div class="some"><label>{{label}}</label><input data-ng-model="ngModel"></div>',

Plunker: http://plnkr.co/edit/9vtmnw?p=preview

 2
Author: Mathew Berg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-01-02 03:10:46

Od Angular 1.5 można używać komponentów. Komponenty są gotowe i łatwo rozwiązują ten problem.

<myComponent data-ng-model="$ctrl.result"></myComponent>

app.component("myComponent", {
    templateUrl: "yourTemplate.html",
    controller: YourController,
    bindings: {
        ngModel: "="
    }
});

Wewnątrz YourController wszystko, co musisz zrobić, to:

this.ngModel = "x"; //$scope.$apply("$ctrl.ngModel"); if needed
 0
Author: Niels Steenbeek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-16 10:07:20

Tworzenie izolowanego zakresu jest niepożądane. Uniknąłbym używania atrybutu scope i zrobił coś takiego. scope: true daje nowy zakres potomny, ale nie izoluje. Następnie użyj parse, aby skierować zmienną local scope do tego samego obiektu, który użytkownik dostarczył do atrybutu ngModel.

app.directive('myDir', ['$parse', function ($parse) {
    return {
        restrict: 'EA',
        scope: true,
        link: function (scope, elem, attrs) {
            if(!attrs.ngModel) {return;}
            var model = $parse(attrs.ngModel);
            scope.model = model(scope);
        }
    };
}]);
 0
Author: btm1,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-18 01:00:06