如何在'指令'中更新'controller'中的值?

时间:2013-09-01 07:13:02

标签: javascript angularjs

我编写了一个'对话'指令用于测试,但我不知道如何在指令中更新控制器的值

app.controller('testController',function($scope){
    $scope.testValue = 'testing';
});

app.directive('testDirectvie',function(){
    return function(scope,element,attr){
         // this func will open the modal window,
         //  so how can I can the testValue from controller?Thx all
    };
});

1 个答案:

答案 0 :(得分:0)

如果添加testDirective的元素在testController中(例如<div ng-controller="testController"><span test-directive=""></span></div>),那么只需直接从指令访问范围。

app.directive('testDirective',function(){
    return function(scope,element,attr){
        scope.testValue = "New value";
    };
});

示例 - http://plnkr.co/edit/lN05YDr4bckrBRPiHyT7?p=preview

如果testDirective超出了testController的范围,那么你需要编写一个共享服务,你可以将它注入到两者中以便共享数据。

控制器和指令共享的服务示例 - http://plnkr.co/edit/lN05YDr4bckrBRPiHyT7?p=preview

相关问题