范围变量在指令中未定义

时间:2014-05-02 10:14:38

标签: javascript angularjs

我正在使用指令我希望在指令中使用范围变量,但它会抛出未定义的错误。

我想用固定号码循环?所以我很紧张 这里的项目是未定义的错误我得到了吗?

是否有任何其他方法来iterrate循环特定没有。时代??

HTML:

<my-dir 
        bgcolor="#EFF"
        my-title="abdullah" 
        my-height="190"
        my-width="160"
        my-color="red"            
        my-bgcolor="blue"
        my-collapseoption=true
        my-widgetno="1"
        save="saveChanges('custom directive')">template
      </my-dir>

脚本:

var app = angular.module('myApp',  ['ngAnimate']);

app.controller('MyCtrl', function($scope, $http) {
   $scope.items = ['a','b','c'];
    });

// add a directive
app.directive("myDir", function() {
  return {
    restrict: "E",
    scope: {
      items:"=",
      myTitle: "@",   // by value
      myHeight: "@",   // by value
      myWidth: "@",   // by value
      myColor: "@",   // by value
      myBgcolor: "@",   // by value
      myWidgetno: "@", // by reference
      myCollapseoption: "@", // by reference            
      save: "&"    // event
    },

    templateUrl:"widget.html", 

    replace: true,
    transclude: false,
    link: function (scope, element, attrs) {

        // show initial values: by-val members will be undefined
       console.log("items is " +scope.items);


        // change element just to show we can
        element.css("background", attrs.myBgcolor);
        element.css("color", attrs.myColor);
        element.css("width", attrs.myWidth+'px');
       // element.css("height", attrs.myHeight+'px');

    }
  }
});

1 个答案:

答案 0 :(得分:0)

您从未将您的items属性传递给指令,因此当指令尝试访问它时,它肯定是未定义的。你的my-dir标签需要提供属性。尝试:

<my-dir 
    items={{items}}
.... />