javascript - 如何在 'controller' 中更新 'directive' 的值?

标签 javascript angularjs

我写了一个“对话”指令用于测试,但我不知道如何在指令中更新来自 Controller 的值

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

最佳答案

如果添加了 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 的范围,那么您将需要编写一个共享服务,您可以将其注入(inject)到两者中以共享数据。

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

关于javascript - 如何在 'controller' 中更新 'directive' 的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18556132/

相关文章:

javascript - JavaScript 中匹配 ${} 的正则表达式

javascript - 从右向左过渡

angularjs - 如何监视也被属性引用的函数

Angular : How do i override directive's style in my view?

angularjs - 查看端口根据用户选择调整大小

javascript - 搜索时如何查看数据而不提交| Angular js

javascript - highcharts - 我如何在热图图例上做自定义标签

javascript - Mobx 存储更改未反射(reflect)在浏览器中

javascript - n 秒后自动关闭 Bootstrap 警报

php - 如何使用angularjs在mysql中存储数学函数值?