【问题标题】:Building an Angular Directive with an ng-if使用 ng-if 构建 Angular 指令
【发布时间】:2014-11-22 02:43:33
【问题描述】:

我想为我的表单使用 Angular 指令,并且基于属性它应该使用输入标签或选择标签。我试图用 ng-if 来做到这一点:

-> 如果设置了选择选项属性,请使用选择标签

通过在指令模板中使用 ng-if,与模型的数据绑定以某种方式变得单向。 (我认为 ng-if 这样做的整个方法是错误的?)

这是一个例子:

<!DOCTYPE html>
<html>
<head>
</head>
<body ng-app="myApp" ng-controller="AppController">
Parent: <input type="number" ng-model="data.a"/><br>
Data.a: {{data.a}}<br/>
Data.b: {{data.b}}<br/>
InputDirective: <my-directive ng-model="data.a"></my-directive>
SelectDirective: <my-directive ng-model="data.b" select-options="{'aa':'Two As','bb':'Two Bs'}"></my-directive>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.3/angular.min.js"></script>
<script>
    var app = angular.module("myApp",[]);

    app.directive('myDirective', function()
    {
        return {
            restrict: 'E',
            scope: {
                value: '=ngModel',
                selectOptions: '='
            },
            template: '<input ng-if="!selectOptions" type="number" ng-model="value"/><select ng-if="selectOptions" ng-model="value" ng-options="k as v for (k,v) in selectOptions"></select>'
        };
    });

    app.controller("AppController", function( $scope )
    {
        $scope.data = {
            a: 54,
            b: 'aa'
        };
    });
</script>
</body>
</html>

【问题讨论】:

  • 不确定,但 ng-model 是特殊属性,尝试使用其他属性传递值并将其分配给 ng-model
  • 我试过了,但没有任何改变。

标签: angularjs angularjs-directive


【解决方案1】:

我找到了解决方案:在模板更改中 ng-model="值" 到 ng-model="$parent.value"

ng-if 正在创建一个子作用域,它正在创建这种问题https://github.com/angular/angular.js/wiki/Understanding-Scopes

我仍然不知道 ng-if 是否是正确的方法。

【讨论】:

  • 这对我帮助很大。谢谢!
猜你喜欢
  • 2013-08-09
  • 1970-01-01
  • 2023-03-09
  • 2017-09-16
  • 2019-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多