【问题标题】:Adding ng-model to div using jQuery使用 jQuery 将 ng-model 添加到 div
【发布时间】:2017-11-17 03:54:09
【问题描述】:

我从 Angular 开始,但遇到了问题。我有这个div。它包含显示来自角度{{stored}} 值的div。当您在文本框中键入内容并单击按钮时。

<div>
  <div id="hidestore">{{stored}}</div> <input id="dobind" type="text" />
  <input type="button" id="showstore" value="show" />
</div>

它调用这个code,它添加了textbox一个ng-model,对应于上面的{{stored}}。 基本上我希望 div 从按下按钮的那一刻起显示{{stored}} 值(不使用$scope)。

$("#showstore").click(function() {
  $("#dobind").attr("ng-model", "stored")
});

对不起,我的语法不好。我需要帮助!

【问题讨论】:

    标签: javascript jquery javascript jquery html css angularjs


    【解决方案1】:

    在 angularjs 中使用jquery 是一种不好的做法,但这并不是说您无法实现您正在尝试的目标。您需要预先绑定它,而不是绑定 ng-model。只需先隐藏hidestore div 并在单击显示按钮后使其显示,这对于angularjs 中的ng-show 是一个非常好的方法。

    angular.module('myApp',[])
    .controller('myAppCtrl',function($scope){
            $('#hidestore').css('display','none');
         $("#showstore").click(function(){
            $('#hidestore').css('display','block');
        });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
     <script data-require="jquery@*" data-semver="3.1.1" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <div ng-app="myApp" ng-controller="myAppCtrl">
    
          <div>
        <div id="hidestore">{{stored}}</div>
        <input id="dobind" type="text" ng-model="stored"/>
        <input type="button" id="showstore" value="show" />
      </div>        
        </div>

    【讨论】:

    • 感谢您回答问题!我假设 $scope 类似于 jquery 中的 $(this)
    • 除了 $scope 之外,您还可以使用不同的约定 @KentaNomoto 。玩得开心编程。你可以google一下:)
    【解决方案2】:

    将 jquery 与 angularjs 一起使用并不是一个好习惯。您需要为输入框创建一个s。和ng-click 按钮功能。当您单击按钮时,将输入框文本分配给stored ng-model。

    angular.module('sample',[])
    .controller('sampleCnt',function($scope){
    $scope.show = function(){
      $scope.stored = $scope.text;
    }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app="sample" ng-controller="sampleCnt">
    
            <div id="hidestore" >{{stored}}</div> <input id="dobind" type="text" ng-model="text"/>
            <input type="button" id="showstore" ng-click="show()" value="show"/>
        </div>
        
        </div>

    【讨论】:

      猜你喜欢
      • 2016-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-11
      • 1970-01-01
      • 2016-02-14
      • 1970-01-01
      相关资源
      最近更新 更多