简体   繁体   English

angularjs-ng-show不起作用

[英]angularjs - ng-show does not woking

I use ng-show to show or hide navigator. 我使用ng-show显示或隐藏导航器。

In index.html : 在index.html中:

<div class="container" ng-show="vm.error" nav></div>

In app.js 在app.js中

var siteApp = angular.module('siteApp', ['ngRoute']);
siteApp.config(function($routeProvider) {
$routeProvider
    .when('/', {
        controller: 'HomeController',
        controllerAs: 'vm',
        templateUrl: '/home.html'
    })
    .when('/404', {
        controller: 'ErrorController',
        controllerAs: 'vm',
        templateUrl: '/404.html'
    });
});

In HomeController.js 在HomeController.js中

siteApp.controller('HomeController', function(){
    var vm = this;
    vm.error = false;
    vm.message = "Halu home page";    
});

In ErrorController.js 在ErrorController.js中

siteApp.controller('ErrorController', function(){
    var vm = this;
    vm.error = true;
    vm.message = "Error 404";
});

My navigator hides in both of pages although vm.message show true. 尽管vm.message显示为true,但我的导航器都隐藏在两个页面中。 Why ? 为什么呢 You can help me at : https://github.com/ryantranvn/mean 您可以通过以下网址帮助我: https//github.com/ryantranvn/mean

As this SO answer discusses regarding using this in place of $scope : 正如这个SO答案讨论有关使用this代替$scope

When using this style, directives should use the controllerAs property in their return object per the Directive documentation. 使用此样式时,伪指令应根据伪指令文档在其返回对象中使用controllerAs属性。

A quick workaround for you would be to preface variable names with $scope if you want them to be available in the view: 对于您来说,一种快速的解决方法是,如果希望变量名在视图中可用,则在它们前面加上$scope

siteApp.controller('HomeController', function(){
    $scope.error = false;
    $scope.message = "Halu home page";    
});

<div class="container" ng-show="error" nav>{{message}}</div>

As to why the text was being hidden in both your test cases, the variable being used in ng-show was not defined. 至于为什么在两个测试用例中都隐藏了文本,则未定义ng-show使用的变量。

Since you are using "this" in the controller function, you will have to declare your Controller with "as" syntax. 由于在控制器功能中使用“ this”,因此必须使用“ as”语法声明Controller。

If you are using routes to bind the controller, add below code in routes 如果您使用路由绑定控制器,请在路由中添加以下代码

controller: "HomeController",
controllerAs: "HomeCtrl"

Or if you are directly writing ng-controller in html, use below code 或者,如果您直接用html编写ng-controller,请使用以下代码

<div ng-controller="HomeCtrl as HomeController">
   <div class="container" ng-show="HomeCtrl.error" nav></div>
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM