尝试使用按钮在$ scope上设置值

时间:2015-07-03 19:37:25

标签: angularjs

我正在尝试使用下面的代码在触摸按钮时在$ scope上设置一个值。它似乎没有起作用 - 我应该怎么做呢?我搜索了很多关于按钮的其他问题,但它们并不是这个特定的问题。

<input type="button" value="Not Important" ng-click="setImportance(1)">
<input type="button" value="Important" ng-click="setImportance(2)">
<input type="button" value="Extremely" ng-click="setImportance(3)">


$scope.setImportance = function (value){
    if (Number(value) == 1){
        $scope.question.importance = "notImportant";
        console.log("$scope.question.importance: " + $scope.question.importance)
    } else if (Number(value) == 2){
        $scope.question.importance = "important";
        console.log("$scope.question.importance: " + $scope.question.importance)
    } else if (Number(value) == 3){
        $scope.question.importance = "veryImportant";
        console.log("$scope.question.importance: " + $scope.question.importance)
    }
    console.log(Number(value));
    console.log("importance is: " + $scope.question.importance)
}

3 个答案:

答案 0 :(得分:3)

由于您没有对value做任何其他事情,因此您可以更轻松地直接在点击上设置值,而不是使用if / else。

<input type="button" value="Not Important" ng-click="question.importance = 'notImportant'">
<input type="button" value="Important"  ng-click="question.importance = 'important'">
<input type="button" value="Extremely"  ng-click="question.importance = 'veryImportant'">

答案 1 :(得分:0)

在控制器中执行此操作的另一种方法是在下面的演示或此jsfiddle中。

&#13;
&#13;
angular.module('demoApp', [])
.controller('mainController', function($scope) {
    var mapping = {
            '1': 'Not important',
            '2': 'Important',
            '3': 'Very important'
        };
    $scope.question = {
        importance: ""
    };
    
    $scope.setImportance = function(value) {
        $scope.question.importance = mapping[value];
    };
    
    $scope.setImportance(1); //init default
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demoApp" ng-controller="mainController">
    <input type="button" value="Not Important" ng-click="setImportance(1)"/>
    <input type="button" value="Important" ng-click="setImportance(2)"/>
    <input type="button" value="Extremely" ng-click="setImportance(3)"/>
    {{question.importance}}
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

还有很多其他方法可以实现您的目标。但是最好先了解代码有什么问题。

在访问该对象的属性之前,需要先初始化对象。具体而言,您需要使用空对象初始化$scope.question。只是让编译器知道它是一个对象。

$scope.question = {};

当您尝试在不初始化时执行$ scope.question.importance时,解释程序将尝试查找问题以检查属性。但它找不到它,因为它没有定义。

让我们用一个非常基本的形象来形象化。

enter image description here

在$ scope.question.importance设置了某个值之后,它将如下所示:

enter image description here 另请注意,您不必使用Number进行投射。两种方式都应该有效,只是不必要

。 然后,它应该工作!

https://jsfiddle.net/rzg53u03/