繁体   English   中英

从指令访问控制器功能

[英]Access controller function from directive

我有一个主控制器: MainCtrl和其中的一个函数: $scope.ctrlFn

此函数需要一个参数并返回连接到接收的参数值的字符串。

MainCtrl JS:

app.controller('MainCtrl', ['$scope', '$http', '$log', '$timeout', function ($scope, $http, $log, $timeout) {
      $scope.ctrlFn = function(x) {
          return 'some val'+x;
      };

      var customTemp = '<div ng-repeat="c in grid.appScope.someArray">{{c}}<my-directive url="MODEL_COL_FIELD" vvv="ctrlFn(url)"  /></div>';
      $scope.someArray=['a','b','c'];      
      $scope.gridOptions = {};

      $http.get('https://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pages/data/500_complex.json')
        .success(function(data) {
          $scope.gridOptions.data = data;

        });
      $scope.gridOptions.rowHeight = 50;  
      $scope.gridOptions.columnDefs = [

        { name:'eee' },
        { name:'age'  },
        { name:'address.street'}
      ];
      $scope.gridOptions2 = {};
      $scope.gridOptions2.data =[];
      $scope.gridOptions2.rowHeight =400;
      $scope.gridOptions2.columnDefs =[];

      var timer = function() {
        for (i = 1; i < 100; i++) { 
          $scope.gridOptions2.data.push({
            value:i,
            name:'Name'+i,
            url:'https://dummyimage.com/30x30/000/fff&text='+i,
            image:i
          });

        }

        $scope.gridOptions2.columnDefs =[
          {
            name:'image',
            cellTemplate:customTemp,
            width:100
          },
          {
            name:'name',
            cellTemplate:customTemp,
            width:100
          },
          {
            name:'url',
            width:50
          },
          {
            name:'value'
          }
        ];

      };

      $timeout(timer,0);
      console.log($scope.gridOptions);
      console.log($scope.gridOptions2);
    }]);

我有一个指令: myDirective ,它创建一个模板并从父作用域变量和函数启动作用域值并显示它们。 我设法将范围变量传递给指令模板,就像使用作用域url一样,但不是myValue值, myValue被赋予从父函数返回的值。

指令myDirective

app.directive('myDirective', function ($log) {

    return {
        restrict: 'E',
        replace: true,

        scope: {
          url: '=',
          vvv: '&'
        },

        template: '<div ng-init="u=url; myValue=vvv" >{{u}}-{{myValue}}<img  src="https://dummyimage.com/100x100/000/fff&text={{url}}" alt="Smiley face" height="100" width="100"></div>',
        link: function (scope, element, attrs) {

          scope.$watch('url', function(newValue) {
            var url = newValue;
          });
        }
    };
});

这是一个吸虫: http ://plnkr.co/edit/yXE3AuZEPwjlmlqpFTNq?p = preview

要从指令模板中访问父作用域,该指令模板在ui grid表格单元格中呈现,您必须通过grid.appScope.variableOrFunction

所以要调用ctrlFn()我必须:

grid.appScope.ctrlFn()

工作示例: http//plnkr.co/edit/yXE3AuZEPwjlmlqpFTNq?p = preview

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM