【问题标题】:AngularJS updating custom directive variableAngularJS 更新自定义指令变量
【发布时间】:2015-08-04 01:51:57
【问题描述】:

我的控制器中有一个变量用作标志。我在指令范围内使用这个变量。我从指令调用我的控制器函数(使用此函数传递指令范围)并尝试更新标志变量,变量在控制器中更新(在 console.log() 中获得更新值)但我没有在指令内获得更新值。

【问题讨论】:

  • 请在此处或 jsfiddle 上复制您的代码。还有你的指令中的范围对象值是什么。

标签: angularjs angularjs-directive


【解决方案1】:

需要您的代码来了解指令和控制器之间的关系。 Here 是我的简单示例。 $scope.test 可以更新。

JavaScript:

angular.module('myApp',[]);

angular.module('myApp').controller('myCtrl',['$scope', function($scope){
  $scope.test='msg from myCtrl';
  $scope.onClick=function(){
    $scope.test='msg from function in myCtrl';
  };


}]);

angular.module('myApp').directive('myDirective', function(){
  return{
    restrict:'E',
    template:'<div>Hello! {{test}}</div><button class="btn btn-default" type="button" ng-click=onClick()>Change value</button>',
    controller:['$scope','$element',function($scope, $element){
      $scope.test='msg from myDirective controller.'
    }],
    link: function(scope, element, attrs){

    },
  };
});

HTML:

<body ng-app='myApp'>
<div ng-controller='myCtrl'>
  {{test}}<br/>
  <my-directive />
</div>
</body>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-11
    • 2014-06-24
    • 2016-07-22
    • 2015-06-21
    • 2017-05-26
    • 2014-03-07
    • 1970-01-01
    相关资源
    最近更新 更多