在我的应用程序中,我想在更新范围变量时执行一些任务。但我的代码只运行页面加载。价值变化时不会触发。
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;
})
});
答案 0 :(得分:2)
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>
答案 1 :(得分:2)
使用$ scope。$ watch:
$scope.$watch('abcd', function(oldValue, newValue) {
if (newValue === ?) {
// do this
}
});
另外,这可能有助于满足一些角度包括jquerylite:
angular.element('.btn').on('click', function() {...})
答案 2 :(得分:1)
你必须在你的控制器中使用$ scope。$ watch来监视abcd值并在它发生变化时对其进行操作。
https://docs.angularjs.org/api/ng/type/$rootScope.Scope
$scope.$watch('abcd', function(val) {
if(val === 'One') {
doWhatever();
}
}