2016-07-16 52 views
0

我有一個指令,這個指令我們編譯ngRepeat正如你看到的。在指令如何可以編譯範圍ngClick上ngRepeat

我的問題是

我不能把從控制器$ scope.delete(),我不知道怎麼可以在我的指令編譯它。

注:運行樣品

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

 
     app.controller("ctrl", function ($scope, $http) { 
 
      var root = "http://jsonplaceholder.typicode.com"; 
 

 
      $scope.list = []; 
 

 
      $http.get(root + "/users").success(function (data) { 
 
       $scope.list = data; 
 
      }); 
 

 
      ///i can't call this scope 
 
      $scope.delete = function (item) { 
 
       alert("delete called"); 
 
      } 
 
     }); 
 

 
     app.directive("mydata", ["$compile", "$filter", function ($compile, $filter) { 
 
      return { 
 
       restrict: "A", 
 
       scope: { 
 
        list: "=" 
 
       }, 
 
       link: function (scope, element) { 
 
        var ngRepeat = element.find(".repeat").attr("ng-repeat", "item in list"); 
 
        $compile(ngRepeat)(scope); 
 
       } 
 
      } 
 
     }]);
<!DOCTYPE html> 
 
<html ng-app="app" ng-controller="ctrl"> 
 
<head> 
 
    <title></title> 
 
</head> 
 
<body> 
 
    <ul id="parent" mydata data-list="list"> 
 
     <li class="repeat"> 
 
      {{item.name}} 
 
      <button ng-click="delete()">delete</button> 
 
     </li> 
 
    </ul> 
 
    
 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
    
 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
    </body> 
 
</html>

回答

1

不知道爲什麼你企圖做這樣的東西,但你的代碼快速的解決方案是用控制器的作用域而不是指令作用域來編譯ngRepeat;

$compile(ngRepeat)(scope.$parent); 

你刪除()將不會觸發,因爲u的您my-data指令創建一個孤立的範圍。 delete()方法不會被繼承。

有關隔離範圍和範圍繼承更多的概念,檢查https://docs.angularjs.org/guide/directive#isolating-the-scope-of-a-directivehttps://docs.angularjs.org/guide/scope

+0

嗨,TNX給你,這是有幫助的,其實我想在我的動態表使用它。 – Maher