小编sah*_*wah的帖子

在DOM中移动控制器时保留元素/范围状态

在角度应用程序中,我想将一个元素从DOM树的一部分移动到另一部分,而不必重新加载附加到移动元素的控制器.

我创建了一个简化的plunker来说明:http://plnkr.co/edit/sqBRM3ZQ5G9xpiNd1MXm?p = preview

在这个plunker中,唯一要保留的数据是toggler状态,但实际上它可能是非常大量的数据,这可能需要花费很多精力才能初始化.

我想要做的是能够将模板1从指令1移动到指令2,但我想保留切换器的状态.在这种情况下,如果单击切换器使其变为绿色,并单击"从列表1移动到2"两次,它将移动到指令2但将颜色重置为红色.

为了避免这种情况,我可以在不通知角度的情况下移动元素,但这显然会创建一个破坏的应用程序状态.

我想过将控制器从旧范围移动到新范围,但我觉得这会导致关闭问题,因为旧控制器可能引用了不再在DOM中的旧元素等.

有没有一个很好的方法来解决这个问题?

添加一些代码因为StackOverflow需要它,但是请参考plunker:

angular.module('app').controller('bodyController', ['$element', function ($element) {

    this.contents1 = [{
        path: 'template1.html'
    }, {
        path: 'template2.html'
    }];

    this.contents2 = [{
        path: 'template3.html'
    }, {
        path: 'template4.html'
    }];

    this.move12 = function () {
        this.contents2.push(this.contents1.pop());
    };

    this.move21 = function () {
        this.contents1.push(this.contents2.pop());
    };

    this.naiveMove12 = function () {
        var $elem = $($element);
        $elem.find('container-list:eq(0) > div').last()
            .appendTo($elem.find('container-list').eq(1));
    };

    this.naiveMove21 = function () {
        var $elem = $($element);
        $elem.find('container-list:eq(1) > div').last()
            .appendTo($elem.find('container-list').eq(0));
    };

    this.logScope …
Run Code Online (Sandbox Code Playgroud)

javascript angularjs

6
推荐指数
1
解决办法
728
查看次数

$ compile和ng-repeat没有返回正确的元素

我不能$compile手动上班ng-repeat.这里有一个类似的问题:由$ compile编译的ngRepeat不起作用,但它没有解决这里的问题,因为我手动调用$digest范围但它仍然无效.

我指的代码在这里:

js:

angular.module('myApp', []);

angular.module('myApp').directive('test', ['$compile', '$rootScope', '$timeout', 
    function ($compile, $rootScope, $timeout) {
        var myScope = $rootScope.$new();
        myScope.numbers = [1, 2, 3];

        var html = '<div ng-repeat="number in numbers">{{ number }}</div>';
        var html2 = '<div>{{ numbers }}</div>';

        var returnObject = $compile(html)(myScope);
        $timeout(function () {
            myScope.$digest();
            console.log(returnObject);
        });

        return {};
    }
]);
Run Code Online (Sandbox Code Playgroud)

HTML:

<html ng-app="myApp">

    <head>
    ...
    </head>

    <body>
        <h1 test>Hello Plunker!</h1>
    </body>

</html>
Run Code Online (Sandbox Code Playgroud)

链接到plunker:http://plnkr.co/edit/RC1EILu16GPr0MGmSpcb?p …

javascript compilation angularjs ng-repeat

2
推荐指数
1
解决办法
1970
查看次数

标签 统计

angularjs ×2

javascript ×2

compilation ×1

ng-repeat ×1