AngularJS隔离范围指令

时间:2016-08-01 06:47:20

标签: javascript angularjs

我在Angular App上设置指令的隔离范围时遇到问题:

这是我的app.js

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

app.controller('mainController', ['$scope', function($scope) {
    if ($scope.name == 'bob') {
        console.log("It's bob")
    }else if ($scope.name == 'joe') {
        console.log("It's joe")
    }else if ($scope.name == 'mary') {
        console.log("It's mary")
    }
}]);

app.directive('test', function() {
    return {
        restrict : 'E',
        replace : true,
        templateUrl :  'test.html',
        scope: {
            name : '@'
        }
        controller : 'mainController'
    };
});

Main.html)看起来像这样:

<div ng-controller="mainController">
      <div>
          /* This is where I set the name in the directive */
          <test name="bob"></test>
      </div>      
</div>

Test.html

<div>{{name}}</div>

现在由于某些原因,当我运行上面的HTML代码时,我的mainController中没有任何print语句发生。

如果我在directive中设置自定义范围对象,那意味着指令test无法访问mainController,这是我传入指令的控制器controller密钥。

4 个答案:

答案 0 :(得分:3)

  

@ binding 用于传递字符串。这些字符串支持{{}}   插值的表达式。例如: 。插值   表达式是根据指令的父范围进行评估的。

     

=绑定用于双向模型绑定。父范围中的模型链接到指令的隔离范围中的模型。改为一个   模型影响另一方,反之亦然。

请在下面找到一个有效的代码示例 - 使用Fiddle链接。

查看

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


app.directive('test', function() {
  return {
    restrict: 'E',
    scope: {
      name: '@'
    },
    controller: 'nameController',
    template: '<div>{{name}}</div>'

  }
})


app.controller('nameController', ['$scope', function($scope) {
  if ($scope.name == 'bob') {
    console.log("It's bob")
  } else if ($scope.name == 'joe') {
    console.log("It's joe")
  } else if ($scope.name == 'mary') {
    console.log("It's mary")
  }else {
    console.log("It's someone else")
  }
}]);

查看Fiddle

答案 1 :(得分:1)

首先使用name : '@'用于单向绑定,即只有当你想使用双向绑定时才需要使用name : '='

答案 2 :(得分:1)

如果使用&#39; @&#39;将属性绑定到范围它基本上会寻找一个字符串。

所以你必须使用以下组合:

name : '@'
<test name={{obj.name}}></test>

name : '='
<test name=obj.name></test>

答案 3 :(得分:0)

你在那里使用了一些递归。当您使用test时,您再次使用mainController,同样在您的模板中。

制作主html文件,在那里使用mainController,然后从test.html中删除ng-controller="mainController"并从指令中删除controller : 'mainController',然后重试。

也请让我们成为一名傻瓜