I have a bunch of templates/views that consist of labels and inputs. I want to set the label values into the controller models ( $scope.data.details
which is an array).
Code: http://plnkr.co/edit/XqtyFKKNuo8upzPuaImo?p=preview
HTML
<body ng-controller="MainCtrl">
<label set-model="data.details[0]">Label 1</label>
<input type=text/>
{{ data.details[0] }}
<label set-model="data.details[1]">Label 2</label>
<input type=text/>
</body>
JS
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.data = {
details: []
};
});
app.directive('setModel', function() {
return {
restrict: 'EA',
link: function(scope, element, attrs) {
// var pair = JSON.parse(attrs)
scope[attrs.setModel] = element.html();
console.log(scope);
// console.log();
}
};
})
So basically:
data.details[0] = "Label 1"
data.details[1] = "Label 2"
...
I know I could do this in ng-init
but it would be a long list on top. I want to do it inline in the <label>
itself.
But right now it doesn't work as $scope
basically shows this in Developer Console:
data: Object
data.details[0]: "Label 1"
data.details[1]: "Label 2"
So it didn't put details
as a key inside data
object but it created a new key data.details[0]
completely. Also the data
structure could be different later on so I don't want to hardcode anything.
How do I fix this?
Or is there a better way to do this?
Try to use this:
<body ng-controller="MainCtrl">
<label set-model="{{data.details[0]}}">Label 1</label>
<input type="text"/>
{{ data.details[0] }}
<label set-model="{{data.details[1]}}">Label 2</label>
<input type=text/>
</body>
Plunker: http://plnkr.co/edit/d9lMXWJDUG6yTxsXFD33?p=preview
If you want result in array only try something like this: http://plnkr.co/edit/KZS1wO1cIvEo7sUpWoDU?p=preview
it does not work this way because when you get key like this 'attrs.setModel' it take whole string which means it takes data.details[0]
you either resolve this with another javascript code just simply using scope
attribute of directive like this
app.directive('setModel', function() {
return {
restrict: 'EA',
scope: {model : '=setModel'},
link: function(scope, element, attrs) {
// var pair = JSON.parse(attrs)
scope.model = element.html();
console.log(scope);
}
};
})
right now your directive take parent scope object instead of string so any value change on this affect parent scope object as well...
here is working PLUNKER ...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.