如何在控制器和$ mdDialog之间共享范围?

时间:2016-04-07 01:41:49

标签: angularjs angular-material

如何在控制器和$ mdDialog(Angular Material)之间共享范围? 我正在使用“Controller As”语法,我需要将我的控制器的功能用于$ mdDialog,因为当它关闭时,我需要一些数据。 在这段代码中,我需要在$ mdDialog中调用“myFunction”。 如果我有一个对象(self.obj)并且我需要它进入'myFunction',当$ mdDialog调用'myFunction'时,该对象不存在于范围内。

angular.module('myApp')
          .controller('myController', myController);

myController.$inject = ['$mdDialog'];

function myController($mdDialog) {

var self = this;
self.obj = {'firstName:'hello','lastName':'world'}


self.myFunction = function () {console.log(JSON.stringfy(self.obj))};

self.showDialog = function (){

    $mdDialog.show({
        controller: function ctrl() {},
        controllerAs: 'ctrl',
        templateUrl: 'views/modal_templates/dialog01.template.html',
        parent: angular.element(document.body),
        targetEvent: ev,
        clickOutsideToClose: true
    })
}

};

2 个答案:

答案 0 :(得分:2)

在您的控制器中:

.controller('testing',
        function($scope,  $mdDialog) {
 $scope.items = [0, 1, 2, 3];
    $scope.addAddress = function(ev)
    {
        $mdDialog.show({
            controller: () => this,
              controllerAs: 'ctrl',
              templateUrl: 'views/address.html',
              targetEvent: ev,
              clickOutsideToClose:true,
              locals: {
                  items: $scope.items,
               },
               });
    };

在address.html中,使用' ctrl'

访问项目
<din ng-repeat="items in ctrl.items">
{{ items }}
</div>

我从以下链接获得此解决方案: https://github.com/angular/material/issues/1531

答案 1 :(得分:0)

您可以使用locals选项注入myFunction。然后使用bind()方法创建一个将此关键字设置为self的新函数。

  

bind()方法创建一个新函数,在调用时,将其this关键字设置为提供的值

public class HandleFromUriParam : IOperationFilter
{
    public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
    {
        string[] splitter = null;
        var fromUriParams = apiDescription.ActionDescriptor.GetParameters().
            Where(param => param.GetCustomAttributes<FromUriAttribute>().Any()).ToArray();

        foreach (var param in fromUriParams)
        {
            var fromUriAttribute = param.GetCustomAttributes<FromUriAttribute>().FirstOrDefault();

            // Check
            if (fromUriAttribute != null)
            {
                var operationParam = operation.parameters;

                foreach (var item in operationParam)
                {
                    if (item.name.Contains(param.ParameterName))
                    {
                        splitter = item.name.Split('.');
                        item.name = splitter[splitter.Length - 1];
                    }
                }
            }
        }
    }
}