0

I have two files as described below. I am defining the controller in file_1.php

In file_2.php, I am 'require'ing the file_1.php, and then moving the ul into the div that is described in file_1.php

What I want to be able to do is - get the functions within the controller to work for the ul which was dynamically added. My guess is that, when the page was loaded, the ul block is seen as being outside the controller and so it doesn't work. On searching, I was able to see a solution that involved $compile, but that works for ng-model, and not for repeat or {{}} either. I am new to Angular and would appreciate any help.

file_1.php

<?php
   <div id="box_1" ng-controller="MyCtrl"></div>
?>

file_2.php

<?php
   require 'file_1.php';
?>

<ul>
   <li ng-repeat="item in items">item.text</li>
</ul>

{{items}}

<script>
   function MyCtrl($scope) {
      $scope.items = [{text: "Item 1", text: "Item 2"}];
   }

   $(document).ready(function() {
          $('#box_1').append($('ul'));
   })
</script>

Some information that I found: In the documentation here, under section "Reasons behind the compile/link separation", they have explained why compiling is different for ng-repeat. Could anyone explain what it means exactly and/or the way to go about it? I tried compile - anything that is not in an ng-repeat works, but anything inside ng-repeat doesn't.

4

2 回答 2

0

出于某种原因,您是否喜欢这种文件结构?你试图做的事情违背了角度,因此会很痛苦。Angular 应该让您摆脱使用 jQuery 进行 DOM 操作的痛苦。

不过,似乎 using$compile应该可以工作。你能告诉我们你想用它做什么吗?

为什么你不能做这样的事情?

<div id="box_1" ng-init="items = [{text: "Item 1", text: "Item 2"}]">
    <ul>
        <li ng-repeat="item in items">{{item.text}}</li>
    </ul>

    {{items}}
</div>

(语法可能有点偏离ng-init.)

于 2012-11-09T17:43:04.180 回答
0

在控制器中操作 DOM 不是一个好习惯。除此之外,$scope.$apply()没有帮助吗?

$(document).ready(function() {
      $('#box_1').append($('ul'));
      $scope.$apply();
})
于 2012-12-20T10:45:58.890 回答