将值设置为视图中的模型

时间:2014-09-01 06:30:46

标签: javascript html angularjs

我有一堆由标签和输入组成的模板/视图。我想将标签值设置为控制器模型($scope.data.details是一个数组)。

代码: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();
    }
  };
})

基本上是这样的:

  

data.details [0] =&#34;标签1&#34;

     

data.details [1] =&#34;标签2&#34;

     

...

我知道我可以在ng-init中执行此操作,但这将是一个很长的列表。我想在<label>本身中内联

但是现在它不起作用$scope基本上在开发者控制台中显示:

data: Object
data.details[0]: "Label 1"
data.details[1]: "Label 2"

因此它没有将details作为data对象中的键,但它完全创建了一个新键data.details[0]。此外data结构可能会有所不同,因此我不想硬编码任何内容。

我该如何解决这个问题?

或者有更好的方法吗?

2 个答案:

答案 0 :(得分:0)

尝试使用它:

  <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

如果你想要数组结果只尝试这样的事情:http://plnkr.co/edit/KZS1wO1cIvEo7sUpWoDU?p=preview

答案 1 :(得分:0)

它不能以这种方式工作,因为当你获得像'attrs.setModel'那样的键时,它会占用整个字符串,这意味着你需要data.details[0]使用另一个javascript代码解决这个问题,只需使用scope像这样的指令的属性

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

现在您的指令采用父作用域对象而不是字符串,因此对此进行的任何值更改都会影响父作用域对象...

这是工作PLUNKER ...