ng-repeat和custom指令的问题

时间:2017-03-26 18:08:25

标签: javascript angularjs

大家好!

我是一个角色新手,因为一个看似简单的问题而疯狂。我正在创建一个指令,它只不过是一个可以变大的“ul / li”。我希望这个指令用来自控制器的数据填充。

我几乎可以做所有事情,但不能做两件简单且相关的任务:

  1. 在“li”。
  2. 中显示字符串属性
  3. 将“li”项作为参数传递给控制器​​中的函数(单击某些“li”)
  4. 你们如何看,它通过对象进行迭代,打印正确数量的对象,但“item”未定义,因此我无法将其作为函数参数传递或在列表中打印。

    ...沮丧

    var app = angular.module("app",[]);
    
    app.controller("AppCtrl", function($scope) {
        $scope.someFunction = function(item) {
          alert("Hello, " + item);
        };
    	
    	$scope.itens = [
    		{id:1,name:'Lorem'},
    		{id:2,name:'Ipsum'},
    		{id:3,name:'Dolor'}
    	];
    });
    
    app.directive("someDirective", function() {
        return {
            restrict: "E",
            // transclude: true,
            scope: {
    			test: "&",
    			loop: "="
    	    },
            template: "<ul><li ng-repeat='item in loop' ng-click='encapsulated(item.name)'>{{item.name}}</li></ul>",
            link: function(scope, element, attrs, controller, transcludeFn) {
    			scope.encapsulated = function(x) {
                    // this function call doesn't work with a parameter
    				scope.test(x);
    			}
            }
        };
    });
    li {
    	color:red;
    	background:yellow;
    	margin-bottom:5px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app="app" ng-controller="AppCtrl">
       <some-directive test="someFunction()" loop="itens"></some-directive>
     </div>

    提前致谢!

1 个答案:

答案 0 :(得分:0)

我能够用@dfsq的提示来解决这个SO答案:Angular: calling controller function inside a directive link function using &。这是解决方案,也许可以帮助其他人:

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

app.controller("AppCtrl", function($scope) {
    $scope.someFunction = function(item) {
      alert("Hello, " + item);
    };
	
	$scope.itens = [
		{id:1,name:'Lorem'},
		{id:2,name:'Ipsum'},
		{id:3,name:'Dolor'}
	];
});

app.directive("someDirective", function() {
    return {
        restrict: "E",
        scope: {
			test: "&",
			loop: "="
	    },
        template: "<ul><li ng-repeat='item in loop' ng-click='encapsulated(item.name)'>{{item.name}}</li></ul>",
        link: function(scope, element, attrs, controller, transcludeFn) {
			scope.encapsulated = function(x) {
				scope.test({arg:x});
			}
        }
    };
});
&#13;
li {
	color:red;
	background:yellow;
	margin-bottom:5px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="AppCtrl">
   <some-directive test="someFunction(arg)" loop="itens"></some-directive>
 </div>
&#13;
&#13;
&#13;