观看ng-model inside指令

 猫儿爱妞_591 发布于 2023-02-07 16:33

我有以下指令:

directive('myInput', function() {
    return {
        restrict: 'AE',
        scope: {
            id: '@',
            label: '@',
            type: '@',
            value: '='
        },
        templateUrl: 'directives/dc-input.html',
        link: function(scope, element, attrs) {
            scope.disabled = attrs.hasOwnProperty('disabled');
            scope.required = attrs.hasOwnProperty('required');
            scope.pattern = attrs.pattern || '.*';
        }
    };
});

使用以下模板:

它由以下形式使用:

The user has been updated.

哪个有这个控制器:

controller('UserDetailsCtrl', function($scope, $stateParams, User) {
    $scope.user = User.get({userId: $stateParams.id});
    /**
     * Update the current user in this scope.
     */
    $scope.update = function() {
        console.log($scope.user);
        $scope.user.$update({userId: $scope.user.id}).then(function(results) {
            $scope.saved = true;
        });
    };
}).

表单渲染正常,但是当我单击Save按钮时,用户值永远不会更新.

如何在控制器范围内的myInput指令中使用更新的值?

1 个回答
  • 这是基本问题.你ng-model是一个原始的,只是在一个方向上绑定...如果父对象被改变它将更新,但由于它是原始的,它不携带对父对象的引用...只是值.因此,更新原语不会更新其原始值来自的父对象

    角度基本规则... 在ng-model中总是有一个点

    这是一个将主user对象传递给指令范围的解决方案,以及用于每个输入的该对象的属性

    <my-input id="firstName" model="user" field="firstName" label="First name"></my-input>
    

    现在需要将对象从控制器传递到指令范围:

    app.directive('myInput', function() {
        return {  
            scope: {
               /* other props*/
                field: '@',
                model:'='/* now have reference to parent object in scope*/
            },
           ......
        };
    });
    

    然后在输入的标记中将使用[]符号来获取我们的:

    <input  ng-model="model[field]".../>
    

    DEMO

    为了使用角度验证你可能将不得不requirengModel控制器的指令或使用嵌套表格

    2023-02-07 16:34 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有