<select> getter-setter接收对象参数为字符串

时间:2015-10-07 11:52:41

标签: javascript angularjs

为什么moo对象参数是[object Object]字符串? &#13; &#13; var App = angular.module(&#39; myApp&#39;,[&#13;     &#39;控制器&#39;]);&#13; &#13; &#13; &#13; var ctrls = angular.module(&#39; controllers&#39;,[]);&#13; ctrls.controller(&#39; myController&#39;,[&#39; $ scope&#39;,function($ scope){&#13;     &#13;     $ scope.moos = [&#13;         {&#39; id&#39;:1,&#39; name&#39;:&#39; foo&#39;},{&#39; id&#39;:2,&#39; name&#39; ;:&#39; boo&#39;}&#13;     ];&#13;     &#13;     $ scope.proxy = {&#13;         setter:function(moo){&#13;             if(!arguments.length)返回;&#13;             的console.log(も);&#13;             $ scope.moo = moo;&#13;         }&#13;     }; &#13; }]);&#13; &lt; script src =&#34; https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0-beta.5/angular.js"&gt;&lt; / script&gt;&#13; &lt; div ng-app =&#34; myApp&#34; NG-控制器=&#34;&myController的#34;&GT;&#13;     &LT; p为H. {{moo.name}}&LT; / P&GT;&#13;     &lt; select ng-model =&#34; proxy.setter&#34; ng-model-options =&#34; {getterSetter:true}&#34;&gt;&#13;         &lt; option ng-selected =&#34; moo.id === m.id&#34; NG-值=&#34; M&#34; ng-repeat =&#34; m in moos&#34;&gt; {{m.name}}&lt; / option&gt;&#13;     &LT; /选择&GT;&#13; &LT; / DIV&GT;&#13; &#13; &#13;

1 个答案:

答案 0 :(得分:1)

ng-value会将字符串放入option的值中。转换为字符串的javascript对象为[object Object]

但是您可以在m.id中添加ng-value以在您的javascript代码中检索它。这是一个例子:

var App = angular.module('myApp', [
    'controllers']);



var ctrls = angular.module('controllers', []);
ctrls.controller('myController', ['$scope', function ($scope) {
    
    $scope.moos = [
        {'id':1, 'name': 'foo'}, {'id':2, 'name': 'boo'}
    ];
    
    $scope.proxy = {
        setter: function (id) {
            if(!arguments.length)  return;
          
            var moo = $scope.moos.filter(function(moo) {
              return moo.id == id;  
            })[0];
          
            console.log(moo);
            $scope.moo = moo;
        }
    };    
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0-beta.5/angular.js"></script>
<div ng-app="myApp" ng-controller="myController">
    <p>{{moo.name}}</p>
    <select ng-model="proxy.setter" ng-model-options="{ getterSetter: true }">
        <option ng-selected="moo.id===m.id" ng-value="m.id" ng-repeat="m in moos">{{m.name}}</option>
    </select>
</div>