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

angularjs unable to assign scope variable inside link function

本文关键字:分配 范围 变量 函数 链接 AngularJS      更新时间:2023-09-26

嗨,我有以下代码片段。我的目标是允许创建多个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];
        }
    }
});

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

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.

知道为什么吗?

由于错误报告"模型"未定义,请尝试从指令的隔离范围中删除model: "="

所以它看起来像这样:

scope: {},