指令模板的角度调用控制器方法

时间:2017-03-23 16:21:26

标签: javascript angularjs angularjs-directive

我用angular创建了一个简单的项目,我使用指令来创建一个像这段代码的简单网格:

我的指示:

app.directive('dpGrid',()=>{
    return{
        restrict:"E",
        scope:{
            items:"="
        }
        templateUrl: 'template/dbgrid.directive.html'
    }

});

我的控制员:

   app.controller('mainCtrl',($scope)=>{

$scope.data=[{fname:"david",lname:"orman",age:24,id:"234"}];

        $scope.update=(id)=>{
          console.log("ID :",id);
        };

    });

我的指令模板:

<table class="table">
    <thead class="thead-inverse">
    <tr>
        <th>#</th>
        <th>fname</th>
        <th>lname</th>
        <th>age</th>
        <th>opt</th>
    </tr>
    </thead>
    <tbody>
    <tr ng-repeat="item in items" >
        <th>{{$index}}</th>
        <td>{{item.fname}}</td>
        <td>{{item.lname}}</td>
        <td>{{item.age}}</td>
        <td><a class="btn btn-danger" ng-click="update(item.id)">update</a></td>

    </tr>
    </tbody>
</table> 

我使用这样的指令:

<dp-grid items="data" ></dp-grid>

我想从指令模板调用update()方法,但是在点击update btn时不要调用update()方法

1 个答案:

答案 0 :(得分:1)

您只需指定指令应使用的控制器,然后在模板中访问它。

var ADAL = new AuthenticationContext({
    instance: 'https://login.microsoftonline.com/',
    tenant: 'common', 
    clientId: '',        //Intentionally left blank here

    redirectUri: 'http://localhost:8383/',     
    callback: userSignedIn,
    popUp: true
});

function signIn() {
    ADAL.login();
}

function userSignedIn(err, token) {
    console.log('userSignedIn called');
    if (!err) {
        console.log(token);            //This works!
        fetchUserSentMails(token);
    } else {
        console.error("error: " + err);
    }
}

function fetchUserSentMails(token) {
    var user = ADAL.getCachedUser();
    console.log(user.profile.name);        //This works!

    $.ajax({                  //This doesn't work
        type: 'GET',
        crossDomain: true,
        url: 'https://outlook.office.com/api/v2.0/me/messages',
        dataType: 'jsonp',
        headers: {'Authorization': 'Bearer ' + token},
        success: function (res) {
            console.log(res);
        },
        error: function (x, t, m) {
            console.log(x);
            console.log(t);
            console.log(m);
        }
    });
}

然后您将能够访问模板中的功能。如果从子隔离范围访问它,则可能需要使用$ parent访问它。

相关问题