gpt4 book ai didi

javascript - AngularJs - 当范围值改变时检查条件(if - else)

转载 作者:行者123 更新时间:2023-11-30 08:35:10 26 4
gpt4 key购买 nike

在我的应用程序中,我想在更新范围变量时执行一些任务。但我的代码只运行页面加载。值变化时不触发。

abcd 值在点击时更新,但 if else 条件未触发。请帮忙

HTML 代码

<div  ng-app="MyApp" ng-controller="BaseController" id="BaseController">
{{abcd}}{{test}}
</div>
<ul>
<li class="btn" data-id="One"><a href="#">One</a></li>
<li class="btn" data-id="Two"><a href="#">Two</a></li>
<li class="btn" data-id="Three"><a href="#">Three</a></li>
<li class="btn" data-id="Four"><a href="#">Four</a></li>
<li class="btn" data-id="Five"><a href="#">Five</a></li>
</ul>

Angular JS 代码

var app = angular.module('MyApp', []);
app.controller('BaseController',['$scope',function($scope){
$scope.abcd = 'testvalue1';
$scope.test = 'test Value 2';
console.log($scope.abcd);
if($scope.abcd === 'One'){
$scope.test = 'First Time';

}else if($scope.abcd === 'Two'){
$scope.test = 'Second Time';

}else if($scope.abcd === 'Three'){
$scope.test = 'Three Time';

}else if($scope.abcd === 'Four'){
$scope.test = 'Four Time';

}else if($scope.abcd === 'Five'){
$scope.test = 'Five Time';

}
}]);

Javascript 代码

 $('.btn').on('click',function(){
var target = $(this).attr('data-id');
var scope = angular.element($("#BaseController")).scope();
scope.$apply(function(){
scope.abcd = target;
})

});

最佳答案

oO 你不应该使用 JQuery

<ul>
<li class="btn" ng-click="abcd='One'"><a href="#">One</a></li>
<li class="btn" ng-click="abcd='Two'"><a href="#">Two</a></li>
<li class="btn" ng-click="abcd='Three'"><a href="#">Three</a></li>
<li class="btn" ng-click="abcd='Four'"><a href="#">Four</a></li>
<li class="btn" ng-click="abcd='Five'"><a href="#">Five</a></li>
</ul>

关于javascript - AngularJs - 当范围值改变时检查条件(if - else),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32112454/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com