Angular Directive生成的输入元素不显示值

时间:2016-08-04 16:03:58

标签: javascript html angularjs

我创建了一个指令,允许我重现一些包含输入字段的HTML。问题是当呈现输入时,值字段使用范围中的值填充但由于某种原因未显示。

无法在Chrome,Firefox或MS Edge中使用。您可以查看此Plunkr

HTML:

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-directive-simple-production</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="docsSimpleDirective">
     <div ng-controller="Controller">
         <form-input i-scope="customer" e-scope="errors" model="customer.name" name="name"></form-input>
     </div>
</body>
</html>

JS

(function(angular) {
'use strict';
angular.module('docsSimpleDirective', [])
.controller('Controller', ['$scope', function($scope) {
$scope.customer = {
  name: 'Naomi',
  address: '1600 Amphitheatre'
};
$scope.errors = {name:"name is required"};
}])
.directive('formInput', function () {
    return {
      restrict: "E",
      scope: {
        formInfo:'=iScope',
        errors:'=eScope'
      },
      replace:true,
      template: function(elem,attr){
        return '<div><input type="text" name="' + attr.name + '" id="' + attr.name + '" ng-model="' + attr.model + '" value="{{ formInfo.' + attr.name + '}}" /><span ng-cloak ng-show="errors.' + attr.name + '">{{ errors.' + attr.name + ' }}</span></div>';
      }
    };
  });
})(window.angular);

更新 请查看Plunkr,因为代码现已更新以显示真正的问题,基本示例使用 @ Stefan.B 中提到的ng-value解决但未解决原来的问题

2 个答案:

答案 0 :(得分:1)

你不应该直接传递范围的完整对象,

控制器: $scope.customer = { ... }

视图: i-scope="customer"

相反,你应该传递对象属性:

控制器:$scope.customer = { customer: { /*same as above */ };

视图: i-scope="customer.customer"

或:

控制器:$scope.customer = { ... }

查看:i-scope-name="customer.name" i-scope-address="customer.address"

会做到这一点。

这里的解释:  https://github.com/angular/angular.js/wiki/Understanding-Scopes

答案 1 :(得分:0)

您可以在模板中使用value更改ng-value return "<div><input type='text' name="+ attr.name + " id=" + attr.name + " ng-model=" + attr.model + " ng-value=formInfo." + attr.name + " /><span ng-cloak ng-show='errors." + attr.name + "'>{{ errors." + attr.name + "}}</span></div>";