每天学习一点点,成功增加一大步

controller 向 directive 传递JSON对象

AngularJS zhanghui 1478℃

这几天的实践学习 AngularJS 时遇到很大的一个坑,就是 controller 在向 directive 传递JSON对象按照书本上的范例去写始终报错执行不成功,在网络上查找了近2天的解决方案也没有查找解决方案,今天在一位做前端同事的帮助下终于解决了。

现在将 controller 向 directive 传递JSON对象的正确写法记录下来

 // 首先在 controller 声明一个JSON对象
app.controller('sidebarCtrl', sidebarCtrlFn];
function sidebarCtrlFn() {
    var vm = this;
    this.test = {name:'aaa'};
};
// 然后在 directive 中获取这个JSON对象
app.directive('menuNav', ['$state', function($state){
    // Runs during compile
    return {
        scope: {
            test: '='
        }, // {} = isolate, true = child, false/undefined = no change
        restrict: 'ECMA', // E = Element, A = Attribute, C = Class, M = Comment
        templateUrl: 'views/sidebar_menu.html',
        replace: true,
        link: function($scope, iElm, iAttrs, controller) {
            console.log($scope.test);
        }
    };
}]);

下面是 controller 向 directive 传递JSON对象中间的HTML部分的代码了

 <menu-nav test="sidebar.test"></menu-nav>

这里要注意的是 test=”sidebar.test” 的写法是和 ng-model 的参数值写法是一样的,不要写成了 test=”{{sidebar.test}}” 网络上和书上很多都是这样的写法这是一个非常误导人的坑。

转载请注明:隨習筆記 » controller 向 directive 传递JSON对象

喜欢 (0)