角指令调用主营范围功能 [英] Angular directive to invoke function on Main scope

查看:87
本文介绍了角指令调用主营范围功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来使用角度,我遇到了一个问题,试图绑定一个函数调用一个孤立的范围。我的指令,类似于这样

  angular.module(对myApp,[])
  .directive(myDirective功能(){
    返回{
      限制:A,
      范围: {
        scopefunc:与&
      },
      链接:功能(范围,ELEM,ATTRS){
         VAR MYVAR = 5;
         scope.handleButton =功能(){
            scope.scopefunc(myvar的);
         }
      }
    };
  })。控制器(myController的功能($范围){
    $ scope.scopefunc =功能(ID){
         警报(ID);
      };
});

在code工作到一个点。如果发生scope.handleButton操作得当调用$ scope.scopefunc主控制器范围但参数MYVAR不传递到主要适用范围 - 它遇到为未定义。谁能告诉我如何传递这个参数回主要适用范围?


解决方案

 < D​​IV NG-应用=对myApp>
  < D​​IV NG控制器=myController的>
    < D​​IV我-指令scopefunc =scopefunc(ID)>< / DIV>
  < / DIV>
< / DIV>angular.module(对myApp,[])
  .directive(myDirective功能(){
    返回{
      限制:A,
      范围: {
        scopefunc:与& scopefunc
      },
      链接:功能(范围,ELEM,ATTRS){
         VAR MYVAR = 5;
         scope.scopefunc({ID:MYVAR});
      }
    };
  })。控制器(myController的功能($范围){
    $ scope.scopefunc =功能(ID){
         警报(ID);
      };
});

演示

I am new to using Angular and I am running into a problem trying to bind a function call to an isolated scope. My directive looks similar to this

angular.module("myApp",[])  
  .directive("myDirective", function () {
    return {
      restrict: "A",
      scope: {
        scopefunc: "&"
      },
      link: function(scope, elem, attrs){
         var myvar=5;
         scope.handleButton = function(){
            scope.scopefunc(myvar);
         }
      }
    };
  }).controller("myController", function ($scope) {
    $scope.scopefunc = function(ID){
         alert(ID);
      };
});

The code works to a point. If the scope.handleButton action occurs it properly invokes the $scope.scopefunc on the main controller scope BUT the parameter myvar is not passed to the main scope - it comes across as undefined. Can someone tell me how to pass this param back to the main scope?

解决方案

<div ng-app="myApp">
  <div  ng-controller="myController">
    <div  my-directive scopefunc="scopefunc(id)"></div>
  </div>
</div>

angular.module("myApp",[])  
  .directive("myDirective", function () {
    return {
      restrict: "A",
      scope: {
        scopefunc: "&scopefunc"
      },
      link: function(scope, elem, attrs){
         var myvar=5;
         scope.scopefunc({ id: myvar });
      }
    };
  }).controller("myController", function ($scope) {
    $scope.scopefunc = function(ID){
         alert(ID);
      };
});

DEMO

这篇关于角指令调用主营范围功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆