我如何使用NG-模型的角度JS指令 [英] How can i use ng-model with directive in angular js

查看:116
本文介绍了我如何使用NG-模型的角度JS指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的指令来递增和递减变量像这样

I have this directive to increment and decrement variable like this

angular.module('shopping')
    .directive('myDir', function () {
        return {
            restrict: 'AE',
            scope: {
                dirModel: '='
            },
            template: '<div><button ng-click="decrement()">-</button>' +
                '<div ng-model="dirModel">{{ value }}</div>' +
                '<button ng-click="increment()">+</button></div>',
            link: function (scope, iElement, iAttrs) {
                scope.increment = function () {
                    scope.value += 20;
                }
                scope.decrement = function () {
                    scope.value -= 20;
                }
            }
        };
    });

我使用这样

&LT;我-DIR dirModel =user.interval&GT;&LT; /我-DIR&GT;

现在,当我点击编辑表单上我的地方范围已经有了 user.interval = 30 然后不被置1。

Now when i click on edit form where my scope already have user.interval = 30 then that does not get set.

有关新的形式,它的工作原理确定

For new form it works ok

推荐答案

工作: HTTP :?//plnkr.co/edit/jjIgVA p = preVIEW

事情你做错了:


  • 在视图中,你需要设置dirModel为DIR-模型

  • in the view you need to set the dirModel as dir-model

在您需要等待dirModel编译,然后将其设置为scope.value指令(你永远不声明它,你可以尝试使用NG-模型股利不正确地)

in the directive you need to wait for dirModel to compile and then set it to scope.value (you never declare it, you may trying to use ng-model in the div incorrectly)

app.directive('MYDIR',函数(){

app.directive('myDir', function () {

return {
    restrict: 'AE',
    scope: {
      dirModel: '='
    },
    template: '<div><button ng-click="decrement()">-</button><div>{{ value }}</div><button ng-click="increment()">+</button></div>',
    link: function (scope, iElement, iAttrs) {
      scope.increment = function () {
          scope.value += 20;
      }
      scope.decrement = function () {
          scope.value -= 20;
      }

      // wait for variable to compile, set it to your value
      var watcher = scope.$watch('dirModel', function() {
        if(scope.dirModel === undefined) return;
        scope.value = scope.dirModel;
        watcher();
      });
    }
  };

});

这篇关于我如何使用NG-模型的角度JS指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆