简体   繁体   English

如何将数据从指令传递到html模板 - AngularJS

[英]How to pass data from directive to html template - AngularJS

In my directive: 在我的指令中:

angular.module('myPopUp',[])
.directive('myPopUp',['$document', function($document){

    return{
        restrict: 'EA',
        controller: function($scope){
        },
        scope: {

        },
        templateUrl: 'popup.html',
        link: function(scope, elm, attr){
        var topPosition = top + (btnHeight/2) - (popOverHeight/2);

        }

After doing the calculation in link, how can I pass 'topPosition' to my popup.html template? 在链接中进行计算后,如何将'topPosition'传递给我的popup.html模板? Any ideas? 有任何想法吗?

I try to do in this way, but it doesn't work. 我尝试这样做,但它不起作用。

popup.html: popup.html:

<div class="popover right" style="width:auto;top:{{topPosition}}px;">
      <div class="arrow"></div>
      <div>.......</div>
    </div>

You can assign you variable to scope , like this 您可以将变量分配给scope ,如下所示

link: function(scope, elm, attr) {
    var topPosition = top + (btnHeight/2) - (popOverHeight/2);
    scope.topPosition = topPosition;
}

Problem solved. 问题解决了。 I added $apply to my codes: 我在代码中添加了$ apply:

link: function(scope, elm, attr) {
var topPosition = top + (btnHeight/2) - (popOverHeight/2);
 scope.$apply(function() {
    scope.topPosition = topPosition;
  }
}

$scope in contoller and scope in link are the same thing. 控制器中的$ scope和链接中的作用域是相同的。 Only difference is that $scope is injected via Dependency Injection whereas in link fxn scope is injected based on position. 唯一的区别是$ scope通过依赖注入注入,而在link fxn范围是基于位置注入。 So for eg 所以对于例如

link: function(element, scope, attr) 

then element will still refer to scope. 那么element仍然会引用范围。

so inside your link function you can assign position to scope like you will assign it in controller only difference is the variable name. 因此,在link功能中,您可以将position分配给范围,就像您将在控制器中分配它一样,区别在于变量名称。 Eg 例如

 .directive('myPopUp', function(){

        return{
            restrict: 'EA',
            controller: function($scope){
                $scope.topPosition = 0; 
            },
            scope: {

            },
            templateUrl: 'popup.html',

            link: function(scope, elm, attr){
                scope.topPosition = 200; // calculate here as per your logic
            }}});

demo 演示

You can refer only scope variables in your template so your scope should have topPosition. 您只能在模板中引用范围变量,因此范围应该是topPosition。

  link: function(scope, elm, attr){
            var topPosition = top + (btnHeight/2) - (popOverHeight/2);
            scope.topPosition = topPosition;  

    }

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

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