Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/388.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 以函数为模板访问重复AngularJS指令中的“$scope”_Javascript_Angularjs_Angularjs Directive_Angularjs Ng Repeat - Fatal编程技术网

Javascript 以函数为模板访问重复AngularJS指令中的“$scope”

Javascript 以函数为模板访问重复AngularJS指令中的“$scope”,javascript,angularjs,angularjs-directive,angularjs-ng-repeat,Javascript,Angularjs,Angularjs Directive,Angularjs Ng Repeat,当指令使用函数作为其模板时,如何从传递到指令的ng repeat访问对象 我在指令中设置了以下ng repeat: <my-directive ng-repeat="item in list.contents" item="item"></my-directive> app.directive('myDirective', function () { return { restrict: 'E', scope: { item: '='

当指令使用函数作为其模板时,如何从传递到指令的
ng repeat
访问对象

我在指令中设置了以下
ng repeat

<my-directive ng-repeat="item in list.contents" item="item"></my-directive>

app.directive('myDirective', function () {
  return {
    restrict: 'E',
    scope: {
      item: '='
    },
    template: function (element, attrs) {
      // pseudo-code
      if (item.type == "typeA")
        return '<li>{{ item }} one type</li>';
      else
        return '<li>{{ item }} another type</li>';
    }
  };
});

app.directive('myDirective',function(){
返回{
限制:'E',
范围:{
项目:'='
},
模板:函数(元素、属性){
//伪码
如果(item.type==“typeA”)
返回'
  • {item}}一个类型
  • '; 其他的 返回“
  • {{item}}另一个类型”
  • ; } }; });
    在模板中,a
    {{item}
    可以正常工作,但是我不知道如何引用
    item
    作为对象,它是通过
    ng repeat
    传入的。使用
    attrs
    可以从标记中获取值,但该值只是一个字符串


    我是否可以将
    类型
    作为对象,因为它被传递到
    ng repeat

    我认为您必须修改您的方法。无法从模板函数访问范围。您可以在模板本身中使用
    ng if
    ,而不是在模板函数中使用
    if
    语句

    例如:

    指令

      app.directive('myDirective',function() { 
         return {
            restrict: 'E',
            scope: { item: '='},
            template: '<div ng-if="item.type==\'one\'">' + 
                          '{{item.name}}' + 
                      '</div>' + 
                      '<div ng-if="item.type==\'two\'">' +
                          '{{item.name}}' + 
                      '</div>'
         }
      });
    

    非常感谢!如果前一段时间被添加到core Angular中,我忘记了
    ng。
    
      <body ng-app="app" ng-controller='ctrl'> 
           <my-directive ng-repeat="item in items" item="item"></my-directive>
      </body>
    
      app.controller('ctrl', function($scope) {
           $scope.items = [];
           $scope.items.push({type:'one', name: 'One'});
           $scope.items.push({type:'two', name: 'Two'});
      });