如何使用自定义指令中的ng-model绑定到视图? - AngularJS

时间:2014-10-17 09:10:33

标签: javascript html json angularjs ng-bind

我正在尝试使用angular JS开发一个应用程序。我创建了一个自定义指令,我试图将值显示到表中。这一切都很好。我无法动态绑定我在文本框中输入的值。以下是我的HTML和JavaScript代码。请帮帮我。提前谢谢。

的index.html

<html ng-app="myApp">

<button ng-click="funJSON()">Test</button>
<table>
    <tbody ng-repeat="field in fields">
        <tr my-dir name="{{name}}" attributes="{{attributes}}"
            ng-repeat="(name, attributes) in field">
        </tr>
    </tbody>
</table>

<!-- I'm trying to bind the values here dynamically. -->
<p>{{test1}} {{test2}}</p>

app.js

var mod = angular.module('myApp', []);

mod.directive('myDir', function() {

var template = function(name, attributes) {

    var tempStr = "<tr>";
    var iteration = 1;
    for ( var column in attributes.column) {

        {
            tempStr += "<td>" + attributes.column[column].label
                    + " : </td>";

            tempStr += "<td>";
            tempStr += "<" + attributes.column[column].tag;
            for ( var attribute in attributes.column[column]) {
                if (attribute != "label" && attribute != "tag") {
                    tempStr += " " + attribute + '="'
                            + attributes.column[column][attribute] + '"';
                }
            }
            tempStr += ' name="' + name + '"';

            tempStr += " ng-model=\"test" + attributes.column[column].ng
                    + "\">";

            // alert(tempStr);

            tempStr += "</" + attributes.column[column].tag + "></td>";

            // alert(tempStr);
        }

        iteration++;
    }
    tempStr += "</tr>";
    return tempStr;
};

return {
    restrict : "AE",
    link : function(scope, element, attrs) {
        var attributes = angular.fromJson(attrs.attributes);
        var html = template(attrs.name, attributes);
        element.html(html);
    }
};


mod.controller('myCtrl', function($scope) {

$scope.funJSON = function() {

    data = {
        "row" : [ {
            "column" : [ {
                "size" : 20,
                "label" : "First Name",
                "type" : "text",
                "tag" : "input",
                "ng" : "1"
            }, {
                "size" : 20,
                "label" : "Last Name",
                "type" : "text",
                "tag" : "input",
                "ng" : "2"
            } ],
            "id" : 1
        } ]
    };
    $scope.fields = data;

};

});

0 个答案:

没有答案