2017-12-18 53 views
0

在下面的代码中,我有一个指令,每次输入字段x被更改时计算变量y。变量y已公开,因此可用于声明控制器/指令。这工作正常,但它是一个简单的抽象,在我真实的情况下,y的计算是非常昂贵的,所以我不能计算y每次x更改。理想情况下,只有在声明控制器/指令需要时才会计算y。有没有办法实现这一点?从指令返回变量而不是暴露示波器

var app = angular.module('app', []); 
app.controller('ctl', function() { 

}); 

app.directive("theDirective", function() { 
     return { 
     restrict: "AE", 
     scope: { 
      y: '=' 
     }, 
     template: '<input ng-model="x" ng-change="xChanged()" />', 
     link: function (scope, element, attrs) { 

      scope.xChanged = function() { 
       scope.y = scope.x * 2; 
      }; 

     } 
    } 
}); 

回答

1

如果从该指令的孩子需要这样的数据,你可以在你的指令控制器暴露的方法,然后露出孩子指令可能要求的方法做到这一点。

app.directive("theDirective", function() { 
    return { 
    restrict: "AE", 
    scope: { 
     y: '=' 
    }, 
    template: '<input ng-model="x" ng-change="xChanged()" />', 
    controller: function (scope) { 

     scope.getY = function() { 
      return scope.x * 2; 
     }; 

    } 
} 
}); 

然后你的孩子可以要求父母可以调用该方法。

app.directive("theDirectiveChild", function() { 
    return { 
    restrict: "A", 
    require: ["^theDirective"], 
    link: function(scope, element, attrs, ctrls){ 

     var theDirective = ctrls[0]; 

     var y = theDirective.getY(); 

    } 
} 
}); 

编辑:反其道而行之,在您想要的家长告诉孩子进行更新,你可以利用$ scope.broadcast()这可以触发一个消息下来作用域链,它会看起来像这个。

app.directive("theDirective", function() { 
    return { 
    restrict: "AE", 
    scope: { 
     y: '=' 
    }, 
    template: '<input ng-model="x" ng-change="xChanged()" />', 
    link: function (scope) { 

     scope.on('update-the-directive' , function() { 
      scope.y = scope.x * 2; 
     }); 

    } 
} 
}); 

然后你的孩子可以要求父母可以调用该方法。

app.directive("theDirectiveParent", function() { 
    return { 
    restrict: "A", 
    link: function(scope, element){ 

     scope.click = function() { 
     scope.$broadcast('update-the-directive'); 
     } 

    } 
} 
}); 
+0

谢谢,但我需要的功能的指令,以从父叫,而不是从编辑我的答案,包括场景,以及一个孩子 – ps0604

+0

。 –

+0

这种方法存在问题。由于'$ broadcast'是异步的,如果子进程中的函数需要时间来处理,则父进程不知道何时结束,因此它不能从该作用域中获取该变量。 – ps0604