【问题标题】:Get data back from angular directive从角度指令获取数据
【发布时间】:2017-08-09 08:25:49
【问题描述】:

我创建了一个名为my-tree 的指令,我从exemple-tree-view.html 视图中调用该指令,如下所示:

<my-tree ng-model="sampleTreeView.listNoeuds" ... />

这个视图的控制器叫做sampleTreeView

在我的指令的链接函数中,我有一个返回一些数据的函数,这些数据会影响到指令控制器中声明的范围变量,如下所示:

function linkFn(scope, element, attrs) {

   //some code

    scope.createNode = function ($event) {
        var sel = $(element).jstree(true).create_node($($event.currentTarget)[0].closest('.jstree-node').id);
        if (sel) {
            $(element).jstree(true).edit(sel, '', function (node, success, cancelled) {
                scope.treeActionsResult.createdNode  = node;
            });
        }
    };

    //some code
}

我的问题是如何在 sampleTreeView 控制器中获取 scope.treeActionsResult.createdNode 值,因为它是我调用指令的 exemple-tree-view.html 的控制器。

【问题讨论】:

    标签: angularjs angularjs-directive


    【解决方案1】:

    您可以通过删除范围属性在指令和控制器之间使用共享范围

    就像这个例子:

    MyApp.directive('studentDirective', function () {
    return {
        template: "{{student.name}} is {{student.age}} years old !!",
            replace: true,
            restrict: 'E',
            controller: function ($scope) {
                console.log($scope);
            }
        }
    });
    

    您仍然拥有 $scope 对象,但在这种情况下,范围对象与父控制器的范围共享。

    您可以从以下链接了解更多信息 Understanding Scope in AngularJs Custom Directive

    【讨论】:

      【解决方案2】:

      如果您不为指令创建隔离范围,那么您可以从控制器访问指令范围值。像下面这样

      你的控制器和指令:

      app.controller('MainCtrl', function($scope) {
        $scope.value = 1;
      });
      
      app.directive('myTree', function() {
        return {
          restrict: 'AE',
          link: function(scope, element, attrs) {
            scope.values = {};
            scope.values.price = 1234;
          }
        };
      });
      

      然后在你的 html 中使用:

      <body ng-controller="MainCtrl">
          <p>value {{values.price}}</p>
          <my-tree att="{{attValue}}"></my-tree>
        </body>
      

      这里 values.price 显示在 MainCtrl 中的指令

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-06-19
        • 2017-11-04
        • 1970-01-01
        • 2019-04-15
        • 2016-07-28
        • 2018-11-06
        • 1970-01-01
        相关资源
        最近更新 更多