如何在指令的ng-repeat中获得ng-model值?

时间:2016-11-08 16:07:40

标签: javascript angularjs angularjs-directive angularjs-ng-repeat angular-ngmodel

我希望在我自己的指令中获得ng-repeat中ng-model的值,并在指令中使用该ng-model的值来实现功能。

这里有一个plunker来查看代码:

https://plnkr.co/edit/MaI8DOtdc4yucXgNo05p?p=preview

这是我的指令代码:

(function() {
  'use strict';
  angular.module('barname.rtEditor', [])
    .directive('rtEditor', rtEditor);

  function rtEditor() {

    return {
      restrict: 'E',
      replace: true,
      templateUrl: 'rt-ht.html',
      compile: compile
    };

    function compile() {

      return {
        post: function(scope, element, attrs) {

          scope.com = {

            inp: [{
              name: 'video',
              model: scope.vimodel,
              command: 'insertHTML',
              modelcommand: scope.vimodel
            }, {
              name: 'pic',
              model: scope.pimodel,
              command: 'insertImage',
              modelcommand: scope.pimodel
            }, {
              name: 'link',
              model: scope.linkmodel,
              command: 'createLink',
              modelcommand: scope.linkmodel
            }]

          };

          scope.$watch('vimodel', function(newValue, oldValue) {
            console.log('vim model watch :-> ', newValue);
          });

          scope.$watch('texmodel', function(newValue, oldValue) {
            console.log('text model watch :-> ', newValue);
          });

          scope.execIn = function(cmd, val) {

            console.log('cmd val :->', cmd + ' | ' + val);

            scope.vimodel = '';
            scope.texmodel = '';

          };
        }
      };

    }
  }
})();

这是html代码:

<div>
  <div ng-repeat="inp in com.inp" id="{{inp.name}}">
    <label>{{inp.name}} :</label>
    <input type="text" ng-model="inp.model" />
    <span ng-click="execIn(inp.command, inp.modelcommand)">doIt!</span>
  </div>

  <br>
  <hr>
  <br>

  <div>
    <label>widout ng repeat:</label>
    <input type="text" ng-model="texmodel" />
    <span ng-click="execIn('textIn', texmodel)">doIt!</span>
  </div>
</div>

我可以轻松获得没有ng-repeat的ng-model的值

0 个答案:

没有答案