angularjs无法在链接函数内分配范围变量

时间:2013-10-13 15:24:32

标签: javascript angularjs angularjs-directive

您好,我有以下代码段。我的目标是允许创建多个div,并将它们的位置,文本,高度和宽度绑定到控制器的模型。

appModule.controller('textController', function($scope){
    var box = {x: '0', y: '0', height: '100px', width: '200px', text: 'this is the default text'};

    $scope.textBoxes = [box];

    $scope.addNewTextBox = function(){
        console.log("creating new textbox!!!");
        $scope.textBoxes.push(box);
    };
});

appModule.directive('tbox', function($document){
    return {
        restrict: "E",
        template: '<div><div ng-transclude></div>',
        transclude: true, 
        scope: {
            model: "=",
        },
        link: function postLink(scope, element, attrs, ctrl){ //the scope here is the object's scope
            var length = scope.$parent.textBoxes.length;
            console.log(length);
            scope.model = scope.$parent.textBoxes[length-1];
        }
    }

});

我遇到了一些问题。我无法将范围的模型变量分配给控制器中的textBoxes变量,说

Error: Non-assignable model expression: undefined (directive: tbox)
    at Error (<anonymous>)
    at h (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js:43:213)
    at Object.<anonymous> (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js:43:326)
    at Object.e.$digest (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js:87:13)
    at Object.e.$apply (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js:89:198)
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js:16:239
    at Object.d [as invoke] (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.

知道为什么吗?

1 个答案:

答案 0 :(得分:0)

由于错误报告了&#39; model&#39;未定义尝试从指令的隔离范围中删除model: "="

所以它看起来像这样:

scope: {},