Angularjs在ng-repeat中的模态指令的奇怪行为

时间:2013-07-05 10:32:39

标签: angularjs angularjs-directive angularjs-ng-repeat

我想要使用模态窗口编辑项目列表。 当我点击每个项目的“编辑”按钮时,我建立了一个指令来打开一个模态窗口,将项目本身传递给模态(带有“form-object”属性)。

但我得到了这种奇怪的行为:

{{formObject}} 始终打印最后一项,而 console.log(scope.formObject)打印正确一个。

这是羽毛球:http://plnkr.co/edit/N5ta15yctYFgmQPqwXr4

1 个答案:

答案 0 :(得分:1)

此处无需compile功能。这有效:

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

  myAppModule.controller('TextController',
        function($scope) {          
            $scope.userModel = [{id:'1',name:'user1'},{id:'2',name:'user2'},{id:'3',name:'user3'}];
        });

    myAppModule.directive('formModal', ['$http', '$compile', function($http, $compile) {
        return {
            scope: {
                formObject: '='
            },
            link: function(scope, element, attrs){
                var template, $element, loader;

                loader = $http.get('modal.html')
                        .success(function(data) {
                            template = data;                               
                        });

                loader.then(function() {
                    $element = angular.element($compile(template)(scope));
                });

                scope.close = function() {
                    $element.modal('hide');
                };

                element.on('click', function(e) {
                    e.preventDefault();
                    $element.modal('show');
                });

            }
        }
    }]);