2015-04-23 81 views
1

我是新来的angularjs,我正在学习指令,我试图将值传递给指令,但是这个东西没有工作。将一个变量的值传递给angularjs指令

HTML

<genericsearch objectType="tei_org" organisationSearch="organisationSearchEvent"></genericsearch> 

指令

directive('genericsearch', [function() { 
return { 
     restrict: 'E', 
     replace: true, 
     scope: { 
     objectType : '=', 

     }, 
    controller: ['$scope','$element','$rootScope','SearchOrg','MapOrgs','$routeParams','DelOrgs','GetTemplateGroups','FetchOrgs', function($scope,$element,$rootScope,SearchOrg,MapOrgs,$routeParams,DelOrgs,GetTemplateGroups,FetchOrgs){ 
     $scope.getOrgs = function(objectType, event) { 
      if(event.keyCode != 13){ 
      //$scope.Participants(data); 
      $scope.organisationSearchEvent(objectType); 
      } 
     } 
     $scope.organisationSearchEvent = function(filter,objectType){ 
      SearchOrg().fetch({'filter':filter, 'searchType':objectType}).$promise.then(

      function(value){ 
      $scope.orgList = value.data; 

      }, 
      function(err){ 

      }); 
     } 
    }], 
    templateUrl : TAPPLENT_CONFIG.HTML_ENDPOINT[0]+'home/search.html' 

} 
}]) 
+0

到底什么是 “不工作”? – gefei

+0

感谢您的回复,但事情是我需要传递tei_org到organizationsearchEvent eventhandler如何通过使用$范围做到这一点,我无法做到这一点。请帮我 – harrini

+0

我觉得属性应该是html中的对象类型而不是objectType。这加上Rouby说的 – sirrocco

回答

0

你似乎曲解$范围和/或如何将值传递到函数。

控制器的$范围有一个属性objectType。您不需要将此作为参数添加到控制器内的功能。

您只需通过$scope.objectType即可访问。

E.g.

$scope.organisationSearchEvent = function(filter){ 
      SearchOrg().fetch({'filter':filter, 'searchType':$scope.objectType}).$promise.then(

      function(value){ 
      $scope.orgList = value.data; 

      }, 
      function(err){ 

      }); 
     } 
-1

这是您使用链接并将其传递到您的控制器的地方。

HTML:

<my-fancy-directive my-attribute="something"></my-fancy-directive> 

的Javascript:

app.directive('myFancyDirective', function() { 
    restrict:'E', 
    replace:true, 
    controller:function($scope){ 
     $scope.theAttribute = ""; 
    }, 

    link:function(scope,elem,attr) { 
     attr.$observe('myAttribute',function(newValue,oldValue){ 
      if(newValue != oldValue) 
      scope.theAttribute = newValue; 
     }) 
    } 
}); 

特别提示:记住变量在linkfunction,只是觉得 “海”。范围,元素,属性

+0

你不需要$观察,这就是范围定义的作用。 – Rouby

+0

此外,我认为这个答案没有解决问题的根源,而只是提供了一种不同的方法。 – Rouby

+0

对不起,显然只是阅读“我正试图将价值传递给指令,但事情没有起作用”,并计算出来。在$观察中,如果属性值更改,您将需要它。 –

0

为此,您可以在您的指令控制器中使用链接功能。

的Html

<genericsearch objectType="tei_org" organisationSearch="organisationSearchEvent"></genericsearch> 

指令

link:function(scope,elem,attrs) {  
     scope.myParam = attrs.organisationSearch; 
     } 

之后,你可以通过你的范围访问myParam在控制器

+0

这已经在指令的范围设置上被角度覆盖了。 – Rouby

+0

感谢您的回复,但我没有定义。 – harrini

+0

@harrini看看我的答案,这个答案不是我想的你的解决方案。 – Rouby

相关问题