AngularJS ng-if 隐藏元素与 ng-select 事件不起作用

AngularJS ng-if hidden elements with ng-select event not work

本文关键字:ng-select 事件 不起作用 元素 ng-if 隐藏 AngularJS      更新时间:2023-09-26

我有一个隐藏的select输入,它被ng-if隐藏了。在隐藏select中,我添加了一个ng-change标签,它反过来调用一个函数来显示一个同样被ng-if隐藏的img

  1. hiddenNinja最初是隐藏的。
  2. 在外部函数上,hiddenNinja显示其元素(例如 select输入(。
  3. 更改 select 的值时,不显示hiddenTommy

但是,如果最初显示hiddenNinja,则只会显示hiddenTommy

以下示例的代码。

.HTML:

<div ng-controller="NinjaController"> // Controller is here
    <div ng-if="hiddenNinja"> // ng-if is here
        <select ng-change="validateFilled()" ng-model="data"> // ng-change & ng-model
            <option selected>First</option>
            <option ng-repeat="item in items" >{{ item }}</option>
        </select>
    </div>
</div>
// Image shown below.
// On the actual code, image is a footer on a different php file,
// Which is also why I use $rootScope in this example.
// For this question, I'll include this image in this partial view.
<img src='randomSource' ng-if='hiddenTommy' />

角:

app.controller('NinjaController',['$scope', '$rootScope', function($scope, $rootScope) {
    $scope.data = "First";
    $scope.items = ['Sight', 'Smell', 'Taste', 'Sight', 'Touch'];
    $scope.validateFilled = function() {
        if ($scope.data != "First") {
            $rootScope.hiddenTommy = true;
        }
    };
}]);

我已经在网上寻找答案,但无济于事。我将不胜感激所提供的任何帮助。

谢谢大家审阅这段代码。

$scope.data

控制器中始终为"First"的原因是,ngIf 指令有自己的作用域,因此当您选择一个值时data只会更改该作用域,而不会更改您期望的范围。在NinjaController中使用$scope.data = { select: 'First' },然后ng-model="data.select" 。因此,没有理由为此创建工厂。在此处阅读有关范围的更多信息:https://github.com/angular/angular.js/wiki/Understanding-Scopes

PS:您应该使用ng-options而不是将ng-repeat放在option上以将项目添加到选择框中,这是一种很好的做法。

已经很长时间了,但好消息是,我设法解决了自己的问题。

.HTML:

<div ng-controller="NinjaController"> // Controller is here
    <div ng-if="hiddenNinja"> // ng-if is here
        <select ng-change="validateFilled(data)" ng-model="data"> // <-- Changed here
            <option selected>First</option>
            <option ng-repeat="item in items" >{{ item }}</option>
        </select>
    </div>
</div>
<img src='randomSource' ng-if='hiddenTommy' />

角度控制器:

app.controller('NinjaController',['$scope', '$rootScope', 'SystemFactory',
    function($scope, $rootScope, SystemFactory) {
    $scope.items = ['Sight', 'Smell', 'Taste', 'Sight', 'Touch'];
    $scope.validateFilled = function(data) {
        SystemFactory.storeOption(data);
        if (SystemFactory.checkIfNotEmpty() == true) {
            $rootScope.hiddenTommy = true;
        }
    };
}]);

角工厂:

app.factory('SystemFactory', [function() {
    var SystemFactory = {};
    // Variable to store selected option
    var selectedOption = "";
    SystemFactory.storeOption = function(temp) {
        selectedOption = temp;
    }
    SystemFactory.checkIfNotEmpty = function() {
        if (selectedOption != "") {
            return true;
        }
    }
    return SystemFactory;
}]);

直到最近才能够解决这个问题。所以我很高兴我设法解决了这个问题,我正在发布这个解决方案,以防有人遇到同样的问题。