【问题标题】:Passing the value in directive to the ng-model. -angularjs将指令中的值传递给 ng-model。 -angularjs
【发布时间】:2017-12-16 16:58:15
【问题描述】:

您好,我正在尝试创建一个指令来将一些值传递给我的 ng-model, 在我的指令中,我的指令中有一个控制器,我想在我的 ng-model 中传递它的值

假设我有一个字符串值,当我单击 $scope.speakUP 时,它应该在 ng-model 上传递它

.directive('speak', function(){
          return {
            restrict: 'A',
             require: 'ngModel',
            scope: true,
            template: '<i ng-click = "speakUP()" class="icon ion-mic-a larger"></i>',

            controller: function($scope, $element){
             $scope.speakUP = function(){

                     $scope.passThisString = "Sample Data";

                 }

        }

这是我的 HTML

  <input type="text" ng-model="sampleModel" speak>

【问题讨论】:

标签: javascript angularjs


【解决方案1】:

这是一个快速示例,您可以从中开始实施您的目标。

 app.directive('inputField', function () {
    return {
        require: '?ngModel',
        template: '<input ng-model="value" ng-change="onChange()"><i ng-click="speakUP()" class="icon ion-mic-a larger">click</i>',
        link: function ($scope, $element, $attrs, ngModel) {
            if (!ngModel) return;

            $scope.speakUP = function(){
              ngModel.$setViewValue('your data');
              ngModel.$render(); 
            }

           $scope.onChange = function() {
             ngModel.$setViewValue($scope.value);
           };

           ngModel.$render = function() {
             $scope.value = ngModel.$modelValue;
           };
        }
    };
});

HTML

<input-field name="sampleModel" ng-model="sampleModel"></input-field>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-26
    • 1970-01-01
    • 2015-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多