AngularJS ng-if带有ng-select事件的隐藏元素不起作用

时间:2014-10-11 06:52:12

标签: javascript html angularjs

我有一个隐藏的select输入,被ng-if隐藏。在隐藏的select中,我添加了一个ng-change标记,该标记又调用了一个显示img的函数,该ng-if也被hiddenNinja隐藏。

  1. hiddenNinja最初是隐藏的。
  2. 根据外部功能,select会显示其元素(例如select输入)。
  3. 更改hiddenTommy的值时,不会显示hiddenNinja
  4. 但是,如果最初显示hiddenTommy,那么只会显示<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' />

    以下示例的代码。

    HTML:

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

    角:

    {{1}}

    我在网上寻找答案无济于事。 如果有任何帮助,我将不胜感激。

    感谢大家审阅这段代码。

2 个答案:

答案 0 :(得分:1)

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

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

Angular Factory:

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

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

答案 1 :(得分:1)

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

PS:您应该使用ng-options而不是ng-repeat option将{{1}}添加到选择框中,这是一个很好的做法。

相关问题