【问题标题】:Angular form directive - how to set ng-model attribute to a value passed in through scopeAngular 表单指令 - 如何将 ng-model 属性设置为通过范围传入的值
【发布时间】:2016-12-27 05:08:48
【问题描述】:

我有这个表格部分(为问题而简化):

<label>firstitem brand: </label><input ng-model="ctrl.object.item_attributes[0].brand">
<label>firstitem model: </label><input ng-model="ctrl.object.item_attributes[0].name">

<label>seconditem brand: </label><input ng-model="ctrl.object.item_attributes[1].brand">
<label>seconditem model: </label><input ng-model="ctrl.object.item_attributes[1].name">

我真的很想做这样的事情:

<form-directive item="ctrl.object.item_attributes[0]"></form-directive>

<form-directive item="ctrl.object.item_attributes[1]"></form-directive>

作为一个 Angular 新手,我对如何通过我的指令设置 ng-model 感到困惑。我试过直接通过范围传递它,并通过指令的链接函数,但没有运气。有什么想法吗?'

编辑:

我根据 Steff 的建议尝试了以下指令:

function fixIt () {
  return {
    restrict: 'EA',
    require: "ngModel",
       link: function (scope, elem, attrs, ngModel) {
           attrs.ngModel = scope.comp
// scope.com = object.item_attributes[i]

       }
  }
};

angular
  .module('app')
  .directive('fixIt', fixIt);

我的输入格式如下:

<input fix-it ng-model="">

我收到以下错误:angular.self-7f8df3e....js?body=1:13921 错误:[ngModel:nonassign] Expression '' is non-assignable。

如果我在我的输入中给 ng-model 一个初始值,那么错误就会消失,但我在 fixIt 指令内的链接函数中没有做任何事情。

【问题讨论】:

    标签: angularjs angularjs-directive angular-ngmodel


    【解决方案1】:

    如果你想通过你的指令设置ng-model,可以考虑如下方法:

    指令代码

    (function(angular) {
        'use strict';
        angular.module('your_module_name',[]).directive('your_directive_name', function() {
        return {
            restrict: "EA",
            require: 'ngModel',
            link: function (scope, elem, attrs, ngModel) {
            // accessing the ng-model value by using attr.ngModel
            }
        };
    });
    })(window.angular);
    

    记得包含你的指令:

    var myApp = angular.module('myapp', [ 'your_module_name']);
    

    HTML 代码

    <input your-directive-name ng-model="">
    

    我将这种方法用于我的 sparkling 指令,它工作得很好。 对于表单验证和其他输入特定设置,您可以查看这个 stackoverflow 问题:Angularjs: form validation and input directive

    如果对您的问题有任何误解,请告诉我,希望对您有所帮助:)。

    编辑:

    我不确定您为什么将ng-model 留空并在指令中绑定$scope 变量。可以试试

    <div ng-repeat="item in ctrl.object.item_attributes">
        <input fix-it ng-model="item">
    </div>
    

    【讨论】:

    • 感谢您的帮助。我尝试通过表单指令和输入指令(如您的解决方案)的链接函数访问 ngModel,但没有骰子。使用您的解决方案会收到一条错误消息:angular.self-7f8df3e....js?body=1:13921 错误:[ngModel:nonassign] Expression '' is non-assignable。元素: errors.angularjs.org/1.5.8/ngModel/…
    • 谢谢。在尝试动态设置 ng-model 又一个小时后,我选择了 ng-repeat 路线。对我来说,ng-repeat 的唯一问题是我希望在我的父控制器中保留未定义的 object.item_attributes 的长度。我最终将它定义为它可能的最大限制,现在只需要在其他地方进行小调整以处理可能具有空索引的对象。
    • 很高兴能帮到你:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-29
    • 1970-01-01
    • 1970-01-01
    • 2014-08-07
    相关资源
    最近更新 更多