2

我想将我的指令的另一个实例附加到父指令中,但我不能使用 $apply 重新编译我的指令。

我想我想念这里的某个地方:)

我的 HTML 代码

<div ng-app="TestApp">
    <div ng-controller="TestCtrl">
        <input ng-model="NewData" />
        <button ng-click="AddNewData($event)">Add New</button>
        <br /><br />
        <div test-collector="testColScope" id="testCol">
            <div test-data="" xx-value="Mouse" xx-href="https://fb.com"></div>
            <div test-data="" xx-value="Keyboard" xx-href="https://goo.gl"></div>
        </div>        
    </div>
</div>

我的 JavaScript 代码

var app = angular.module('TestApp', []);

app.controller('TestCtrl', ['$scope', function($scope){   

    $scope.AddNewData = function($event){

        // i also want to access this but it shows undefined
      console.log("test-collector", $scope.testColScope);

      var div = $('<div></div>')
        .attr(
            {
                "test-data":"",
                "xx-value":$scope.NewData,
                "xx-href":"http://p.com"
            });       

        //$scope.$apply(function(){
            $('#testCol').append(div);  
        //});        
    };
}]);

app.directive("testCollector", function () {
    return {
        restrict: "A",
        scope: {

        },
        transclude: true,  
        replace: true,
        controller: function($scope) {
            console.log($scope);
        },
        link: function(scope, element, attrs) {
            console.log(attrs);
            scope[attrs.testCollector] = {
                Enteng : 'Dagpin'
            };
        },
        template: '<div>' +
                        '<ul><div ng-transclude></div></ul>' +
                   '</div>'
    }
});

app.directive("testData", function(){
    return {
        restrict: "A",
        require: '^testCollector',
        transclude: true,
        replace: true,
        scope: {
            xxValue: '@',
            xxHref: "@"
        },
        template: '<li><a href="{{xxHref}}">{{xxValue}}</a></li>'
    }
});

这是摆弄问题

4

2 回答 2

1

要了解已插入的 Angular 新元素,您需要首先使用$compile服务编译该元素,$compile(div)($scope)然后只有您可以将该元素附加到 Angular DOM 中。

而且你的指令已经在 html 上呈现,所以 div 结构发生了变化。

而不是 $('#testCol') 使用angular.element('#testCol ul div')

这是工作小提琴

更新 1

根据@enzey DOM 操作不应该在控制器内部完成。它应该在指令内部完成。这就是@Vincent & 我在小提琴中做出改变的原因。DOM 操作逻辑已移至内部指令。

这是更新的小提琴

于 2015-01-19T07:00:01.533 回答
0

您正在尝试从控制器中进行 DOM 操作。更改 DOM 是指令的目的。这是您需要解决的第一件事。

至于向 DOM 中的子元素添加指令,您只需要使用指令的编译功能即可。

Module.directive('name', function () {
    return {
        compile: function ($element, $attrs) {
            \\ here
        }
    }
}
于 2015-01-19T07:05:59.907 回答