2014-10-07 49 views
0

我已經在外殼頁面(index.html)中初始化了一個屬性,我想在通過route.my代碼調用的控制器中獲取該值。如何獲得在外殼頁面初始化爲控制器的屬性值

的index.html:

<html> 
    //loaded all libraries,modules 
    <ng-init="status=false"></ng-init> 
    <ng-init="activator=[{'orders':'active'},{'customers':''},{'about':''}]"></ng-init> 
    <ul class="nav nav-tabs nav-justified" role="tablist" ng-show="status"> 
    <li class="activator.orders"><a href="#customers">Customers</a></li> 
    <li class="activator.customers"><a href="#orders">Orders</a></li> 
    <li class="activator.about"><a href="#about">About</a></li> 
    </ul> 

<ng-view></ng-view> 

</html> 

orderscontroller.js

app.controller('ordersctrl',function($scope,$rootScope,$http,$cookies,$cookieStore,$location) 
{ 
$rootScope.status="true"; 
$rootScope.myname=$cookieStore.get('name'); 
alert($rootScope.activator); //it prints "undefined" 
}); 

customermanager.js

var app=angular.module('customermanager',['ngRoute','ngCookies','ngAnimate','ui.bootstrap']); 

app.config(function($routeProvider) 
      { 

    $routeProvider.when('/', 
         { 

    controller:'loginctrl', 
    templateUrl:'views/loginview.html' 

    }) 
    .when('/orders', 
         { 

    controller:'ordersctrl', 
    templateUrl:'views/ordersview.html' 

    }) 
    .when('/customers', 
         { 

    controller:'customersctrl', 
    templateUrl:'views/customersview.html' 

    }) 
    .when('/about', 
         { 

    controller:'aboutctrl', 
    templateUrl:'views/aboutview.html' 

    }) 
    .otherwise(
     { 
     redirectTo:'/' 

     }); 

}); 

當我點擊「#orders」,orderscontroller.js及其相關的看法是called.My要求是通過「激活」屬性orderscontroller.js,請幫助。 ..

回答

0

首先,ngInit指令有一個屬性:restrict: 'AC'這意味着創建<ng-init/>元素將無法正常工作。

什麼是ngInit「允許您評估當前範圍中的表達式」(請參閱​​https://docs.angularjs.org/api/ng/directive/ngInit)。所以,如果你想初始化HTML中的值,你應該在控制器的「範圍」內執行它,那就是你應該在其中使用ngController指令和相應的ngInit指令。

<div ng-controller="ordersctrl"> 
    <span ng-init="..." /> 
    ... 
</div> 

<div ng-controller="ordersctrl" ng-init="...">...</div> 

我想,你應該也能這裏面ng-app(嘗試將其添加到您<html>標籤)。

但它至少還不夠優雅。爲什麼你想在HTML中初始化你的變量?當您定義它們時,您可以將這些值分配給您的控制器,就像您使用$rootScope.status時所做的那樣。

+0

我使用「角路由」來映射視圖和控制器...和我需要得到的屬性「激活」是在外殼頁面(index.html),我想要在任何控制器中訪問該屬性我我已經更新了我的代碼。希望很明顯。 – 2014-10-07 12:32:25

+0

嘗試將'ng-init'更改爲某個節點的屬性。 – 2014-10-07 12:41:35