为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

倚天杖 2019-10-05 11:00:42
我正在尝试创建一个指令,该指令将创建与创建指令的元素具有相同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>的JavaScriptvar 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"从模板中删除后,这似乎工作正常。但是,我将继续公开这个问题,因为我想再次确认这是正确的方法。
查看完整描述

3 回答

?
12345678_0001

TA贡献1802条经验 获得超5个赞

它并不那么复杂:在命令中,使用别名: scope:{alias:'=ngModel'}


.directive('dateselect', function () {

return {

    restrict: 'E',

    transclude: true,

    scope:{

        bindModel:'=ngModel'

    },

    template:'<input ng-model="bindModel"/>'

}

在您的html中,照常使用


<dateselect ng-model="birthday"></dateselect>


查看完整回答
反对 回复 2019-10-05
  • 3 回答
  • 0 关注
  • 598 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信