angularJS动态范围定义隔离范围自定义指令定义

时间:2015-03-16 10:01:24

标签: angularjs angularjs-directive

我有一个孤立的范围自定义指令说

<my_isolate_scope_dir  columns="columns" />

指令定义就像这样。

 .directive("myIsolateScopeDir", ["$compile","$templateCache",function($compile,$templateCache){
    return {
    restrict: 'E',
    scope: {
        columns: '=',
            },
    templateUrl: 'customdirective.html',

    }
    }]);

问题是,在指令定义scope:{}中我可以动态定义另一个范围变量,其值来自父范围变量columns

父控制器可以是

$scope.columns=[{"name":"x","isLink":true,"onClickFunction":"clickedx"},{"name":"y","isLink":true,"onClickFunction":"clickedy"}]
$scope.clickedx=fucntion()
{
 console.log("x is clicked");
}

我希望我的自定义指令scope定义为

    scope: {
        columns: '=',
        clickedx: '&', //this is added dynamically to the definition based on the value in columns array
        clickedy: '&' //this is added dynamically to the definition based on the value in columns array
            },

让我知道这是否可以通过相同的方式实现,或者是否有其他更简单的方法来实现这一目标。

1 个答案:

答案 0 :(得分:1)

您可以使用$parse手动将方法注入范围。

link: function (scope, element, attrs) {
    if (scope.columns) {
        scope.columns.forEach(function (column) {
            if (column.onClickFunction) {
                // column.onClickFunction is a string(eg, clickedx), we need to treat this as a function in scope
                var fn = column.onClickFunction + "()";

                // get a reference to the function defined in the scope
                var getParentMethod = $parse(fn);

                // Use of Locals: apart from accessing the properties of the scope, you will be able to pass few properties using locals, which will have the precedence over the properties of scope

                // For example if the markup is -- <button on-click="test(arg1, arg2)"
                // arg1, arg2 needs to be evaluated in the scope
                // As isolateScope breaks the inheritance chain, we need to pass element.scope() to the parser function to access the arg1, arg2 properties from controllers scope

                // define a method in the scope with the value of column.onClickFunction (eg, clickedx)
                scope[column.onClickFunction] = function (locals) {

                    // when scope.clicedx is executed execute the method defined in the controller. 
                    return getParentMethod(element.scope(), locals);
                }
            }
        })
    }
}