从分离范围指令获取控制器模型 [英] Getting controller model from isolate scope directive

查看:73
本文介绍了从分离范围指令获取控制器模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有一个十亿关于这里分离范围的问题,但我无法找到一个直接关系到这个确切的问题。

I know that there are a billion questions about isolate scope on here, but I could not find one that directly relates to this exact issue.

我有我叫模式,所以.. $ scope.Model 控制器上的财产。然后,我有一个需要与模型进行交互指令。

I have a property on my controller called Model, so .. $scope.Model. I then have a directive that needs to interact with the Model.

我想给该指令的适用范围分离,但这被证明是有点困难,因为这样做就意味着我不再能够访问模式。我以为我可以通过指定模型作为双向的分离范围绑定,这样的解决这个问题。

I am wanting to give the directive an isolate scope, but this is proving a bit difficult because doing that means I no longer have access to the model. I thought I could solve this by specifying the model as a two-way binding in the isolate scope, like this.

<body ng-app="app" ng-controller="HomeController">
   <div custom-directive="Model.Tags"></div>
</body>

的JavaScript

app.directive('customDirective', ['$parse', function($parse) {
   return {
      restrict: "A",
      scope: {
         customDirective: "=Model"
      },
      link: function(scope, element, attributes){
         // need to access the controller's "$scope.Model" here for some things.
         var model = scope.$eval(attributes.customDirective);
      }
   }
}])
.controller('HomeController', ['$scope', function($scope) {
   $scope.Model = {
      Id: "items/1",
      Name: "Some Model Object",
      Tags: []
   };
}]);

我真的失去了,为什么这是行不通的。根据所有的分离范围教程,我见过的,这应该是罚款。

I'm really lost as to why this doesn't work. According to all of the isolate scope tutorials I've seen, this should be fine.

传递控制器作为参数不是一个选项。第三方库,我需要与已经这样做了互动,显然我不能这样做,两次相同的HTML元素。

Passing the controller as a parameter is not an option. A third party library that I need to interact with already does this, and apparently I can't do that twice on the same HTML element.

推荐答案

您使用不正确。这将工作:

Your usage is incorrect. This will work:

<body ng-app="app" ng-controller="HomeController">
   <div custom-directive="Model"></div>
</body>


app.directive('customDirective', [function() {
   return {
      restrict: "A",
      scope: {
         customDirective: "="
      },
      link: function(scope, element, attributes){
          console.log(scope.customDirective); // this is the $scope.Model due to 2-way binding
      }
   }
}])
.controller('HomeController', ['$scope', function($scope) {
   $scope.Model = {
      Id: "items/1",
      Name: "Some Model Object",
      Tags: []
   };
}]);

这篇关于从分离范围指令获取控制器模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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