双向绑定指令+控制器

时间:2016-06-07 09:06:24

标签: javascript angularjs

我在DOM中动态添加文本字段(来自指令链接功能)&想要获取输入的值并将其推送到控制器范围对象,但它总是给我未定义,下面是我的代码:

<div class="input-group">
    <span class="fieldIcon input-group-addon"><i class="fa fa-sticky-note" aria-hidden="true"></i></span>
    <select name="addlist[]" multiple="multiple">
        <option ng-repeat="options in optionList">{{options.label}}</option>
    </select>
</div>
<script type="text/javascript">
    angular.module('myapp')
    .controller('AddContactController',[ '$scope', function ($scope) {
        $scope.optionList = [{label: 'NewList'}];        

        $scope.addOption = function(optionList) {
            console.log('List:', optionList); // its giving undefined
            scope.optionList.push(optionList);
        }

    }])
    .directive('optionList', ['$compile', function ($compile) {
        return {
            restrict: 'E',
            templateUrl: '/templates/int_optionList.html',
            controller: 'AddContactController',
            link: function(scope, element, attrs) {
                // Adding input field and on click of a button controllers addOption function should be called with the text field value
                var addListField = '<input class="form-control" type="text" ng-modal="addList" name="addList" placeholder="Add new list...">'+
                +'<button class="btn btn-default" type="button" ng-click="addOption()">';

                addListField = $compile(addListField)(scope);
                $(element).find('.multiselect-container').prepend(addListField);
            }
        }
    }]);
</script>

现在在addOption函数中我将optionList值视为未定义。

2 个答案:

答案 0 :(得分:1)

错误是人类:)。 在指令

中用ng-model替换ng-modal

答案 1 :(得分:0)

AngularJS希望模型采用对象形式,设置ng-modal =&#34; addList&#34;到ng-modal =&#34; data.addList&#34;可能有所帮助。