在指令内更改范围时查看不更新

时间:2016-07-05 12:24:31

标签: javascript angularjs

如何从指令更新范围?这是一个显示我想要的示例代码。

html

<div ng-controller="sampleController">
    <sample-directive></sample-directive>
    {{message}}
</div>

JS

var app = angular.module('sample')
    .controller('sampleController',function($scope){
        $scope.message = "Foo";
        $scope.bar = function(){
            $scope.message = "Bar";
        }
    }).directive("sampleDirective",function(){

        return {
            controller : "sampleController",
            restrict : "E",
            template : "<button type='button' ng-click='bar()'></button>"
        }
    });

单击该按钮时,$scope.message将更改为条形,但视图未更新。(已回答)

这是另一个场景:

html

<div ng-controller="sampleController as sc">
    <sample-directive message="bar"></sample-directive>
    {{sc.message}}
</div>

JS

var app = angular.module('sample')
    .controller('sampleController',function(){
       var sc = this;
       sc.message = "foo";
       sc.bar = function(){
          //change the sc.message to value that is passed to the message attribute in the sample directive
       }
    }).directive("sampleDirective",function(){
        return {
          restrict : "E",
          template : "<button type='button' ng-click='sc.bar()'></button>",
          scope : {
            message : "@"  //how can I pass this to the sc.message scope?
          }
        }
    })

1 个答案:

答案 0 :(得分:2)

您没有将$scope注入您的控制器。

.controller('sampleController',function($scope) {
  ...
}

您正在创建控制器的两个实例: 一个在这里:<div ng-controller="sampleController"> 另一个用于指令controller : "sampleController"

每个实例都有不同的$ scope,所以当你在指令中调用bar()时,它会更新指令范围内的$ scope.message,但不会超出它。

您可以省略controller : "sampleController",,那么您将只有一个范围。 (尽管您的指令仅适用于<div ng-controller="sampleController">