2016-04-15 61 views
0

我看到了很多的反應,此NG單擊但所有使用$scope

我有幾個ng-models有幾個按鈕來增加或減少價值,我想只爲所有人使用一個功能。

像這樣:

app = angular.module("myApp",[]); 
 

 
app.controller("myCtrl", mainFunction); 
 

 
function mainFunction(){ 
 
    scope = this; 
 
    this.value1 = 3; 
 
    this.value2 = 5; 
 
    this.addOne = function (control) { 
 
     if (scope.control <12){ 
 
      scope.control += 1; 
 
     } 
 
    } 
 

 
    this.dimOne = function (control) { 
 
     if (scope.control > 1) { 
 
      scope.control -= 1; 
 
     } 
 
    } 
 
    }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="myApp" ng-controller="myCtrl as vm"> 
 

 
    <span>{{vm.value1}}</span> 
 
    <button ng-click="vm.dimOne('value1')">-</button> 
 
    <button ng-click="vm.addOne('value1')">+</button> 
 
    <br /> 
 
    <span>{{vm.value2}}</span> 
 
    <button ng-click="vm.dimOne('value2')">-</button> 
 
    <button ng-click="vm.addOne('value2')">+</button> 
 
    
 
</div>

+0

也許你可以改變span的內部html? – 2016-04-15 12:40:48

回答

0

因爲你似乎路過的你想要的字符串,只需更新您的功能:

this.addOne = function (control) { 
    if (scope[control] < 12) { 
     scope[control] += 1; 
    } 
} 

this.dimOne = function (control) { 
    if (scope[control] > 1) { 
     scope[control] -= 1; 
    } 
} 

而且...是你的HTML應該是這樣?

<span>{{vm.value1}}</span> 
<button ng-click="vm.dimOne('value1')">-</button> 
<button ng-click="vm.addOne('value1')">+</button> 
<br /> 
<span>{{vm.value2}}</span> 
<button ng-click="vm.dimOne('value2')">-</button> 
<button ng-click="vm.addOne('value2')">+</button> 
+0

是的,有一個錯誤的HTML,我已經修復它。謝謝! – distante

1

只是通過實際的model: -

<button ng-click="vm.dimOne(vm.value2)">-</button> 

*.js

this.dimOne = function (control) { 
    if (control > 1) { 
     control -= 1; 
     this.value2 = control ; 
    } 
} 
+0

編輯,這是我的錯誤 – manish

+0

這將無法正常工作,value1會如何更新? –

+0

你對那裏有一個單獨的方法與需要的功能 – manish