scope。$ eval在angular.js指令中不起作用

use*_*624 0 angularjs angularjs-directive

我想构建一个angular.js指令,通过单击<span>,它将变成可编辑的输入。并且以下代码运行良好,除了模型为空或模型长度为0时,请使其显示为<span> EMPTY </span>

  <span  ng-editable="updateAccountProfile({'location':profile.location})" ng-editable-model="profile.location"></span> 

app.directive('ngEditable', function() {
    return {
        template: '<span class="editable-wrapper">' + '<span data-ng-hide="edit" data-ng-click="edit=true;value=model;">{{model}}</span>' + '<input type="text" data-ng-model="value" data-ng-blur="edit = false; model = value" data-ng-show="edit" data-ng-enter="model=value;edit=false;"/>' + '</span>',
        scope: {
            model: '=ngEditableModel',
            update: '&ngEditable'
        },
        replace: true,
        link: function(scope, element, attrs) { 

           var value = scope.$eval(attrs.ngEditableModel);
           console.log('value ' , attrs.ngEditableModel , value);
           if (value == undefined || (value != undefined && value.length == 0)) {
             console.log('none');
             var placeHolder = $("<span>");
             placeHolder.html("None");
             placeHolder.addClass("label");
             $(element).attr("title", "Empty value. Click to edit.");
           }


            scope.focus = function() {
                element.find("input").focus();
            };
            scope.$watch('edit', function(isEditable) {
                if (isEditable === false) {
                    scope.update();
                } else {
                    // scope.focus();
                }
            });
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

问题发生在代码的这一部分

    var value = scope.$eval(attrs.ngEditableModel);
    console.log('value ' , attrs.ngEditableModel , value);
Run Code Online (Sandbox Code Playgroud)

attrs.ngEditableModel输出内容'profile.location',但是使用scope。$ eval()仅输出'undefined',即使模型'profile.location'不为null

Mar*_*idt 5

您有两种方法可以解决此问题。

1)您在错误的作用域上调用$ eval。你必须scope在你的链接功能,新创建的隔离范围。attrs.ngEditableModel确实包含对指令外部范围的引用,这意味着您必须在scope。$ parent处调用$ eval。

scope.$parent.$eval(attrs.ngEditableModel)
Run Code Online (Sandbox Code Playgroud)

或2)一种更好的处理方式:您已经通过的范围定义绑定了ngEditableModel

scope: {
    model: '=ngEditableModel',
Run Code Online (Sandbox Code Playgroud)

因此,您无需使用自己的$ eval调用,而只需使用scope.model指向的值即可attrs.ngEditableModel。这已经是双向的。