更新控制器变量并在指令视图中使用它(角度1.5)

时间:2016-10-01 01:59:13

标签: javascript angularjs

我想从子指令更新控制器变量。 我更新了控制器变量,但该值在视图中没有变化。 需要我使用$ scope。$ apply()? $ digest?

这是我的代码http://plnkr.co/edit/zTKzofwjPfg9eXmgmi8s?p=preview

js file

var app = angular.module('app', []);

app.controller('parentController', function($scope) {
    this.myVar = 'Hello from parent';

    this.refreshMyVar = function(data) {
        this.myVar = data.name;
        console.log('>> this.myVar', this.myVar);
    };
});

app.directive('myDirective', function() {
    return {
        restrict: 'E',
        replace: true,
        template: '<input type="file" />',
        bindToController: {
            attrFromParent: '='
        },
        controller: 'directiveController as directiveCtrl',
        link: function(scope, el, attr, ctrl) {
            el.bind('change', function(e) {
              ctrl.onChange(e.target.files[0]);
            });
        }
    };
});

app.controller('directiveController', function() {
    this.onChange = function(file) {
        this.attrFromParent(file);
    };
});

html文件

 <!DOCTYPE html>
<html lang="en-US">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="app.js"></script>
<body>

<div ng-app="app" ng-controller="parentController as parentCtrl">
  <h1> >> {{parentCtrl.myVar}}</h1>
  <p><my-directive attr-from-parent="parentCtrl.refreshMyVar" /></p>
</div>

</body>
</html> 

如果您有其他建议让我的代码干净,请分享

更新

app.controller('parentController', function($scope) {
    this.myVar = 'Hello from parent';

    this.refreshMyVar = data => {
        this.myVar = data.name;
        console.log('>> this.myVar', this);
        $scope.$parent.$apply(); // solve my problem
    };
});

$ $范围父$申请();但如果有人有其他主张,我不会很满意

1 个答案:

答案 0 :(得分:1)

首先,您的my-directive元素语法错误。它不应该是一个不是有效HTML的自闭元素。

语法应如下

<my-directive attr-from-parent="parentCtrl.refreshMyVar"></my-directive>

第二重要

app.controller('parentController', function($scope) {
    var vm = this;
    vm.myVar = 'Hello from parent';
    this.refreshMyVar = function(data) {
      // You should not directly refer "this" inside refreshMyVar function 
      // since "refreshMyVar" function is executed in context of directive 
      // "this" will refer "myDirective" controller scope
      // console.log("this :" this); // try to uncomment and see what "this" holds
      // If you use "vm" you will be able to get hold of actual "myVar" due to
      // closure formed by refreshMyVar function when it was created.
      // console.log("vm :" vm); // try to uncomment and see what "vm" holds
      // Reading about closures(JavaScript concept) will help you.
      vm.myVar = data.name;
      console.log(vm);
      alert('>> this.myVar ' + vm.myVar);
      // Since refreshMyVar is executed in context of directive, you have do
      // $apply on parent scope to apply changes
      $scope.$parent.$apply();
    };
});

工作plunker

article也可以为您提供帮助。