angularjs重复指令的范围函数

时间:2015-02-12 22:00:02

标签: angularjs

我正在尝试使用重复指令并让它调用父控件和子控件上的函数。但是当我添加一个范围时:{function:& function} 重复停止正常工作。

fiddle

main.html就像是

<div ng-app="my-app" ng-controller="MainController">
    <div>
        <ul>
        <name-row ng-repeat="media in mediaArray" on-delete="delete(index)" >
        </name-row>
        </ul>
    </div>
</div>

main.js

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

function MainController($scope)
{
    $scope.mediaArray = [
        {title: "predator"},
        {title: "alien"}
    ];
    $scope.setSelected = function (index){
        alert("called from outside directive");
    };
    $scope.delete = function (index) {
        alert("calling delete with index " + index);
    }

}

module.directive('nameRow', function() {
    return {
        restrict: 'E',
        replace: true,
         priority: 1001, // since ng-repeat has priority of 1000
        controller: function($scope) {
            $scope.setSelected = function (index){
                alert("called from inside directive");
            }
        },
        /*uncommenting this breaks the ng-repeat*/
        /*
        scope: {
        'delete': '&onDelete'
        },
        */
        template:
'            <li>' +
'                <button ng-click="delete($index);">' +
'                    {{$index}} - {{media.title}}' +
'                </button>' +
'            </li>'
    };
});

2 个答案:

答案 0 :(得分:1)

正如klauskpm所说,将共同逻辑转移到独立的服务或工厂更好。但我看到的问题是ng-repeat与你指令的元素相同。尝试将您的指令嵌入循环内的元素中,并在该元素的属性中传递函数,或者在您的指令中创建一个模板,该模板在模板中使用ng-repeat

<li ng-repeat="media in mediaArray" >
    <name-row on-delete="delete(media)" ></name-row>
</li>

答案 1 :(得分:0)

正如我所建议的那样,分享方法的更好方法是建立工厂或服务,就像下面这样:

app.factory('YourFactory', function(){
    return {
        setSelected: function (index){
            alert("called from inside directive");
        }
    }
};

你会这样称呼它:

function MainController($scope, YourFactory) {
    $scope.setSelected = YourFactory.setSelected;
    // Could even use $scope.yf = YourFactory;, and call yf.setSelected(index);
    // at your view. 
    (...)

module.directive('nameRow', function(YourFactory) {
    (...)
    $scope.setSelected = YourFactory.setSelected;
    (...)

希望它会对你有所帮助。