ng-repeat from within innerHTML function?

前端 未结 2 1124
一整个雨季
一整个雨季 2021-01-23 12:17

I have 3 columns. The first lists a list of subjects from an array. Within that array, each subject has it\'s particular courses listed within, and within that, the rest of the

相关标签:
2条回答
  • 2021-01-23 12:29

    No, it won't work.

    You need to use template or directive.

    http://docs.angularjs.org/guide/directive

    You simple move innerHTML string to directive template

    .directive('myCustomer', function() {
      return {
        scope: {
              subject: '='
        },
        template: '<string here>'
      };
    });
    

    And use it like

    <my-customer subject="xxx"/>
    
    0 讨论(0)
  • 2021-01-23 12:38

    A directive is a better answer for you. DOM manipulation should be done in directives, not controllers.

    That said, it is possible using Angular's $compile which makes Angular aware of new HTML.

    Just as a proof of concept- here's that function (and a working fiddle):

    $scope.showDetail = function (todo) {
        var html= '<div><a ng-repeat="course in subjects['+todo+'].courses" class="list-group-item" target="#courseinformation" ng-click="showDetail(course)">{{course.coursesub}}</a></div>';
        var innerHTML =$compile(html)($scope) 
        var currente = angular.element(document.getElementById("courselistings"));
    
        currente.replaceWith(innerHTML);
    }
    

    In order for this to work we also need to pass in the index of the course you want to show -- ng-click="showDetail($index)". This is because the $compile will compile this against the controller scope, not the one inside the ngRepeat.

    As you can see it takes jumping through a number of hoops to make this work- which is part of why a directive is better.

    0 讨论(0)
提交回复
热议问题