AngularJS-创建使用ng-model的指令

我正在尝试创建一个指令,该指令将创建与创建指令的元素具有相同ng-model的输入字段。


到目前为止,这是我想到的:


的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);

    }

  };

});

但是,我不确定这是处理这种情况的正确方法,并且存在一个错误,即我的控件未使用ng-model target字段的值初始化。


这是上面代码的简称:http ://plnkr.co/edit/IvrDbJ


处理此问题的正确方法是什么?


编辑:ng-model="value"从模板中删除后,这似乎工作正常。但是,我将继续公开这个问题,因为我想再次确认这是正确的方法。


倚天杖
浏览 612回答 3
3回答

12345678_0001

它并不那么复杂:在命令中,使用别名: scope:{alias:'=ngModel'}.directive('dateselect', function () {return {&nbsp; &nbsp; restrict: 'E',&nbsp; &nbsp; transclude: true,&nbsp; &nbsp; scope:{&nbsp; &nbsp; &nbsp; &nbsp; bindModel:'=ngModel'&nbsp; &nbsp; },&nbsp; &nbsp; template:'<input ng-model="bindModel"/>'}在您的html中,照常使用<dateselect ng-model="birthday"></dateselect>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

AngularJS