将数组绑定到指令模型

时间:2016-05-11 23:25:28

标签: angularjs data-binding angularjs-directive

我能够在此示例中绑定独立字符串:http://plnkr.co/edit/GKZHSDe5J0eCzqlgaf4g?p=preview

然而,当尝试相同但使用字符串数组时,模型不再更新:http://plnkr.co/edit/Fz9GFxWeZxRpsiqXgra4?p=preview

这是指令代码:

app.directive('psDIR', [
    function() {
        return {
            template: "<div ng-init=\"models=['yp', 'hi']\" style='padding: 5px; border: 1px solid red; margin-bottom: 10px;'><p>This is a direcive:</p> <textarea ng-repeat=\"md in models\" rows='5' cols='50' ng-model='md'></textarea></div>",
            restrict: 'AEC',
            scope: {models:'=model'},
            link: function (scope, elm, attrs, ctrl) {
              scope.$watchCollection('scope.models', function(){
                  console.log(scope.models);
              });
            }
        }
    }
]);

模型不再与数组匹配,我做错了什么?

1 个答案:

答案 0 :(得分:0)

app.directive('psDIR', [
    function() {
        return {
            template: "<div ng-init=\"models=['']\"><textarea ng-repeat=\"md in models track by $index\" ng-model='models[$index]'></textarea></div> {{validation}}",
            restrict: 'AEC',
            scope: {validation: '@', models:'=model'},
            link: function (scope) {
              scope.$watchCollection('models', function(){
                console.log(scope.models);
              });
            }
        }
    }
]);