AngularJs -当作用域值改变时检查条件(if - else)

AngularJs - check condition (if - else ) when scope value change

本文关键字:条件 if else 检查 作用域 改变 AngularJs      更新时间:2023-09-26

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

abcd value在点击时更新,但如果其他条件未触发。请帮忙

<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;
    })
});

你不应该使用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>

use $scope.$watch:

$scope.$watch('abcd', function(oldValue, newValue) {
    if (newValue === ?) {
       // do this
    }
});

也,这可能有助于满足一些,角包括jqueryite:

angular.element('.btn').on('click', function() {...})

您必须使用$scope。$watch在控制器中监视abcd值,并在它发生变化时对其进行操作。

rootScope.Scope美元https://docs.angularjs.org/api/ng/type/

$scope.$watch('abcd', function(val) {
    if(val === 'One') {
      doWhatever();
    }
}