Reputation: 342
I have created a directive which allows me to reproduce some HTML which includes an input field. The problem is when the input is rendered the value field is populated with the value from the scope but for some reason is not being displayed.
Not working in Chrome, Firefox or MS Edge. You can have a look at this 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);
UPDATE Please have a look at the Plunkr as the code is now updated to show the true issue, the basic example was solved using ng-value as mentioned by @Stefan.B but does not solve the original problem
Upvotes: 0
Views: 309
Reputation: 465
You shouldn't pass directly the full object of the scope,
controller:
$scope.customer = { ... }
view:
i-scope="customer"
instead you should pass the object properties:
controller: $scope.customer = { customer: { /*same as above */ };
view:
i-scope="customer.customer"
or:
controller: $scope.customer = { ... }
view: i-scope-name="customer.name" i-scope-address="customer.address"
would do the trick.
Explanation here: https://github.com/angular/angular.js/wiki/Understanding-Scopes
Upvotes: 1
Reputation: 146
You can change value
with ng-value
in your template.
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>";
Upvotes: 0