在$scope variable angularjs中获取ng模型



我有这个html代码:

<select class="" ng-model="livre_selection" material-select multiple watch>
                <option ng-repeat="livre in livres">{{livre.titre }}</option>
            </select>

我可以在控制器中获取"livre_selection",并将其放入控制器中的一个变量中,以便使用它吗?

感谢

是的,AngularJS有双向数据绑定。您在ng模型中放入的任何内容都将通过$scope对象在控制器中可用。在您的情况下,您可以通过$scope.livre_selection 访问它

是的,你可以得到它。下面的例子。检查ng-changeng-click函数。你可以同时使用这两个函数,也可以只使用一个函数。

<html>
  <body ng-app="myApp" ng-controller="yourCtrl">
    <select  ng-model="livre_selection" ng-change="a();" material-select multiple watch>
    <option ng-repeat="livre in livres">{{livre.titre }}</option>
    </select>
    <input type="button" value="save" ng-click="b();">
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
    <script>
    var app = angular.module('myApp', []);
    app.controller('yourCtrl', function($scope) {
      $scope.livres=[{titre:"a"}]; 
      var selectedValue;
      $scope.a = function(){
        selectedValue = $scope.livre_selection;
      }
      $scope.b = function(){
        alert(selectedValue);
      }
    });   
    </script>      
  </body>    
</html>

尝试

$scope.livre_selection = '';

因为$scope基本上是一个映射,但更可取的做法是使用upperCase变量命名,比如:

$scope.liveReSelection = '';

之后,您将能够访问控制器中的此变量。

你可以在这里阅读更多。

  • 控制器

    $scope.livre_selection = ""; <br>

    var localVariable = "";

    $scope.changeValue=function(changedVal){ localVariable = changedVal; }

  • HTML

  • 在控制器附近的html中写一个ng更改
    <select class="" ng-change="changeValue(livre_selection)" ng-model="livre_selection" material-select multiple watch> <option ng-repeat="livre in livres">{{livre.titre }}</option> </select>

最新更新